I am beginner in Laravel.
I use in my project Laravel 7.
I have cache system in my project.
I have cache in my project with keys:
category
category.id
category.subcategory.id
product.all
etc.
I need function to remove cache.
I write this:
private function deleteCache(string $keyToRemove)
{
Cache::forget($keyToRemove);
}
Is universal cache removal possible?
I need a function that will be
Remove selected keys:
deleteCache(['category.100', 'product.all', 'category.1'])
Remove all cache with category (for example: category.1, category.all, category, category.tree, category.subcategory.1 etc).
deleteCache(['category.*'])
How can I make it?
TL:DR What you need is not available by default, you need customized, wrapper methods that requires "technical" knowledge about the cache driver(underlying technology) you choose.
Laravel cache supports multiple technologies(drivers) including redis, database, file, memcached etc. All these drivers implement the same interface.
namespace Illuminate\Contracts\Cache;
interface Store
{
/**
* Retrieve an item from the cache by key.
*
* #param string|array $key
* #return mixed
*/
public function get($key);
/**
* Retrieve multiple items from the cache by key.
*
* Items not found in the cache will have a null value.
*
* #param array $keys
* #return array
*/
public function many(array $keys);
/**
* Store an item in the cache for a given number of minutes.
*
* #param string $key
* #param mixed $value
* #param float|int $minutes
* #return void
*/
public function put($key, $value, $minutes);
/**
* Store multiple items in the cache for a given number of minutes.
*
* #param array $values
* #param float|int $minutes
* #return void
*/
public function putMany(array $values, $minutes);
/**
* Increment the value of an item in the cache.
*
* #param string $key
* #param mixed $value
* #return int|bool
*/
public function increment($key, $value = 1);
/**
* Decrement the value of an item in the cache.
*
* #param string $key
* #param mixed $value
* #return int|bool
*/
public function decrement($key, $value = 1);
/**
* Store an item in the cache indefinitely.
*
* #param string $key
* #param mixed $value
* #return void
*/
public function forever($key, $value);
/**
* Remove an item from the cache.
*
* #param string $key
* #return bool
*/
public function forget($key);
/**
* Remove all items from the cache.
*
* #return bool
*/
public function flush();
/**
* Get the cache key prefix.
*
* #return string
*/
public function getPrefix();
}
Depending on the driver you choose - you need customized methods to achieve what you need.
For your first question, the following method would be useful to remove multiple keys.
public function deleteCache(array $keys)
{
foreach ($keys as $key) {
Cache::forget($key);
}
}
I am familiar with redis so i will give examples around it. If you are going to use redis as cache driver - it is better to modify that method like this; Since redis's delete command supports deleting multiple keys at once. This one is more effective than the previous one.
public function deleteCache(array $keys)
{
Redis::del($keys);
}
One trick is to be careful about cache prefix. If you are using cache prefix(defined in your cache config file) - then you need to prepend those prefix to keys.
For your second question(Remove all cache with category) there are several ways to do it but some of them wouldn't be performance/production friendly. In redis you may execute some command such as keys or scan to iterate through database and then invoke the previously defined method with the returned results.
Especially keys command should only be used in production environments with extreme care.
redis key
redis scan
Redis is only example - if you are going to use database cache driver - then you need to implement methods to satisfy your case. It will require technical knowledge about the both how laravel implements it via database(tables, queries etc) and how your extended methods will use it(tables, queries, columns, indexes etc)
Related
Is there a way with php-cs-fixer to define an order for Symfony annotations/PHPDoc ?
Here is two examples of a controller method and an entity property :
/**
* #Security()
*
* #ParamConverter()
*
* #Rest\Post()
* #Rest\View()
*
* #param Request $request
* #param xxxInterface $item
*
* #return \FOS\RestBundle\View\View
*/
public function myAction(Request $request, xxxInterface $item)
and
/**
* #var itemInterface
* #ORM\ManyToOne()
* #ORM\JoinColumn()
* #JMS\Groups()
* #JMS\AccessType()
* #MyCustomAssert\Assert1
*/
protected $item;
For methods, I want to set the order to #Security, #ParamConverter, #Rest then PHPDoc and for properties, I always want #MyCustomAssert at the end.
Is this something possible with php-cs-fixer ?
I think it isn't possible with php-cs-fixer (https://mlocati.github.io/php-cs-fixer-configurator/?version=2.9#version:2.15 might help searching)
However the slevomat coding standard for php code sniffer includes a sniff "SlevomatCodingStandard.Commenting.DocCommentSpacing" which allows you to configure annotationsGroups
The phpcbf script can reorder your annotations using this snif.
Is it possible to link to another method/class/property/etc. inside my project inline inside the #deprecated tag? Like this:
/**
* Method description
* #deprecated 1.0 Reason for deprecation, use {#link newMethod()} instead!
* #param string $str
* #param string|null $str2
* #return bool
*/
public function method($str, $str2) {
// TODO: Code...
}
...
?
According to PHPdoc.org, you could use the #see tag for that.
/**
* #see http://example.com/my/bar Documentation of Foo.
* #see MyClass::$items For the property whose items are counted.
* #see MyClass::setItems() To set the items for this collection.
*
* #return integer Indicates the number of items.
*/
function count()
{
<...>
}
Also, PHPdoc.org recommends to use #see in case of a #deprecated method:
It is RECOMMENDED (but not required) to provide an additional description stating why the associated element is deprecated. If it is superceded by another method it is RECOMMENDED to add a #see tag in the same PHPDoc pointing to the new element.
But #see is not always required, for example "Link to another method in #param tag's description?"
I have created PHP7 project in Zend Studio 13 and I get warnings like this Call to undefined function 'dba_open'. Why Zend Studio didnt recognize these functions?
dba_open
dba_close
dba_fetch
mhash
Any ideas how to solve this?
Zend doesn't ship language support for all the extensions in Zend Studio.
The most efficient way of adding support for language entities provided by unsupported extensions is definitely creating stubs.
The description "stub" files for all supported PHP entities can be found in this directory:
/.metadata/.plugins/org.eclipse.php.core/language
And this is also the location where you should put your stub files.
Copy PHP code from below. Create a file DBA.php and put it into a folder
workspace/.metadata/.plugins/org.eclipse.php.core/__language__/languagecode/DBA.php
languagecode - 8 hex digit name
You won't be able to debug a code having those functions, but at least there will be no warnings anymore.
<?php
/**
dba_open() establishes a database instance for path with mode using handler.
#link http://php.net/manual/en/function.dba-open.php
#param path string <p>Commonly a regular path in your filesystem.</p>
#param mode string <p>It is r for read access, w for read/write access to an already existing database,
c for read/write access and database creation if it doesn't currently exist, and n for create,
truncate and read/write access. The database is created in BTree mode, other modes (like Hash or Queue)
are not supported.<br>
<strong>Note:</strong><br>
There can only be one writer for one database file. When you use dba on a web server and more than
one request requires write operations they can only be done one after another. Also read during write
is not allowed. The dba extension uses locks to prevent this.
</p>
#param handler string <p>The name of the handler which shall be used for accessing path. It is passed all
optional parameters given to dba_open() and can act on behalf of them.</p>
#return FALSE on failure or positive handle on success.
*/
function dba_open ( $path , $mode, $handler=null) {}
/**
* dba_exists() checks whether the specified key exists in the database.
* #link http://php.net/manual/en/function.dba-exists.php
*
* #param string $key <p>The key the check is performed for.</p>
* #param mixed $handle <p>The database handler, returned by dba_open() or dba_popen().</p>
* #return Returns TRUE if the key exists, FALSE otherwise.
*/
function dba_exists ( $key , $handle ) {}
/**
* dba_fetch() — Fetch data specified by key
* #link http://php.net/manual/en/function.dba-fetch.php
*
* #param string $key The key the data is specified by.
* <p><div><h3>Note:</h3></div>
* When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().
* </p>
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return Returns the associated string if the key/data pair is found, FALSE otherwise.
*/
function dba_fetch ( $key , $handle ) {}
/**
* dba_fetch() — Fetch data specified by key
* #link http://php.net/manual/en/function.dba-fetch.php
*
* #param string $key The key the data is specified by.
* <p><div><h3>Note:</h3></div>
* When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().
* </p>
* #param $skip The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return Returns the associated string if the key/data pair is found, FALSE otherwise.
*/
function dba_fetch ( $key , $skip , $handle ) {}
/**
* dba_delete — Delete DBA entry specified by key
* #link http://php.net/manual/en/function.dba-delete.php
*
* #param mixed $key The key of the entry which is deleted.
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return Returns TRUE on success or FALSE on failure.
*/
function dba_delete ( $key , $handle ) {}
/**
* dba_replace — Replace or insert entry
* #link http://php.net/manual/en/function.dba-replace.php
*
* #param mixed $key The key of the entry to be replaced.
* #param mixed $value The value to be replaced.
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return Returns TRUE on success or FALSE on failure.
*/
function dba_replace ( $key , $value , $handle ) {}
/**
* dba_insert() inserts the entry described with key and value into the database.
* #link http://php.net/manual/en/function.dba-insert.php
*
* #param string $key <p>The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.</p>
* #param string $value <p>The value to be inserted.</p>
* #param mixed $handle <p>The database handler, returned by dba_open() or dba_popen().</p>
*
* #return Returns TRUE on success or FALSE on failure.
*/
function dba_insert ( $key , $value , $handle ) {}
/**
* dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.
*
* #link http://php.net/manual/en/function.dba-firstkey.php
*
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return Returns the key on success or FALSE on failure.
*/
function dba_firstkey ( $handle ) {}
/**
* dba_nextkey() returns the next key of the database and advances the internal key pointer.
*
* #link http://php.net/manual/en/function.dba-nextkey.php
*
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return Returns the key on success or FALSE on failure.
*/
function dba_nextkey ( $handle ) {}
/**
*
* #link http://php.net/manual/en/function.dba-close.php
*
* #param mixed $handle The database handler, returned by dba_open() or dba_popen().
* #return No value is returned.
*/
function dba_close ( $handle ) {}
Here's a definition of the field for the main document:
/**
* #var ArrayCollection
* #MongoDB\ReferenceMany(
* targetDocument="Some\Namespace\Document\Reference",
* sort={"creationDate": "desc"},
* simple=true
* )
* #Expose
* #Groups({"Main"})
* #Type("ArrayCollection<Some\Namespace\Document\Reference>")
* #var \Some\Namespace\Document\Reference[]
*/
protected $references;
I tried to get a list of main documents and serialized them via JMS Serializer, but I found, that references is empty array. After some investigation, I discovered, that for getReferences, documents returns instance of PersistentCollection for which:
count returns 2 [ok]
getMongoData returns array of MongoIds [ok]
toArray returns empty array [invalid]
Looks like that's because of initialize method, that clears mongoData.
I achived the proper outcome with following code:
/**
* #VirtualProperty
* #SerializedName("reference_ids")
* #Groups("Main")
* #return array
*/
public function getReferenceIds()
{
$out = array();
foreach ($this->getReferences()->getMongoData() as $val) {
$out[] = (string)$val;
}
return $out;
}
But it's only a shortcut and I don't feel, that's a proper solution.
If anyone has an idea how to retrieve these ids or whole documents using PersistentCollection and why initialize method clears mongoData ?
Thanks.
Is there anyway to give text editors summary information in a tooltip for custom functions/classes etc. in the way that they can do for standard libraries while coding?
Failing this what is the standard way to highlight the purpose, required params etc. for a function/class in PHP.
Check out PHPDocumentor.
An example would be:
/**
* Set the data
*
* #access public
* #param string $field
* #param mixed $value
*/
public function __set($field, $value)
{
$this->_data[$field] = $value;
}
/**
* Get the data
*
* #access public
* #param string $field
* #return mixed
*/
public function __get($field)
{
return isset($this->_data[$field]) ? $this->_data[$field] : NULL;
}
As the comments self-explain, you use #access to show the visibility of the method (if the code being summarized is a method, of course), #paramto show each parameter, and #return to show the type of the data being returned. There are many different tags to document many different aspects of the code.
You can use the PHPDoc standard for letting your IDE give you hints about, for example, a function.
Just before a function declaration you could have:
/**
* This is a DocBlock comment
*/
function foo(){
//....
}
I've used it in Netbeans and can say that it works quite nicely.