Yii Framework-Data caching
- Configuration of Yii cache:
Yii directory/config/web.php file, configure the value of class array under the cache array, default to Yii\caching\filecache.
2. Use of the cache:
To get the cache component:
$cache=\yii::$app->cache;
To add cached data:
$cach->add (key, value[,time][,dependency]);
Parameters: |
Key |
Key |
|
Value |
Value |
|
Time |
Optional, cache expiration |
|
Dependency |
Optional, dependency mode |
return value: |
|
|
To modify the cached data:
$cach->set (key, value[,time]);
Parameters: |
Key |
Key |
|
Value |
Value |
|
Time |
Optional, cache expiration |
return value: |
|
|
Note: If multiple modifications are made to the same key at the same time, only the first modification is valid.
To delete cached data:
$cach->delete (key);
Parameters: |
Key |
Key |
return value: |
|
|
Get Cached data:
$cach->get (key);
Parameters: |
Key |
Key |
return value: |
|
|
Empty the cache:
$cach,flush();
3. Cache dependency:
There are three ways to rely on caching: file dependencies, expression dependencies, db dependencies, chain dependencies, group dependencies. Only the first three dependencies are described here.
File dependencies:
// declaring dependent methods and dependent files $dependency=new \yii\caching\filedependency ([' filename ' = ' test.txt ']); // associated caches and dependencies $cache->add (' key1 ', ' Hello world! ',$dependency);
If the file changes, the associated cache is invalidated.
Expression dependency:
// declaring dependency patterns and dependency expressions $dependency=new \yii\caching\expressiondependency ([' expression ' = ' = ' \yii\:: $app- >requests->get ("name") ']); // associating a cache with a dependency $cache->add (' key1 ', ' Hello world! ',$dependency);
If the expression result changes, the associated cache is invalidated.
DB dependency:
// declaring dependency patterns and relying on SQL statements $dependency=new \yii\caching\dbdependency ([' sql ' = ' = ' SELECT coun (*) from Yii ']); // associated caches and dependencies $cache->add (' key1 ', ' Hello world! ',$dependency);
If the result of the SQL statement execution changes, the associated cache is invalidated.
Yii Framework-Data caching