For the product often need to generate some cache class things, such as the system basic configuration, commodity classification, each modification after adjusting to manually cache publishing, is not very troublesome! This is when the Yii2.0 cache relies on publishing to play a vital role! The main use flow is introduced as follows:
1. A new Update_time field is added to the data table that needs to cache the dependent publication, and the value of update_time is changed after each addition and modification of the record:
2. Ensure that data tables that rely on publishing are cached each time you save (including update operations), you can update the value of Update_time:
//base basemodel.php for all table model inheritance /** * @name rewrite Yii2.0 BeforeSave method to achieve the purpose of automatically updating cache fields Update_time * @author testme * @date 2016-12-06 * @see \y Ii\db\baseactiverecord::beforesave ($insert)*/ Public functionBeforeSave ($insert) { //to define a table that needs to set up a dependent cache $cacheTable=[SysConfig:: TableName (),Syscodedetail:: TableName (),Sysmenu:: TableName (), ]; $cacheTable=Array_flip($cacheTable); if(array_key_exists($this->tablename (),$cacheTable) &&$this->hasattribute (' Update_time ')) { $this->setattribute (' Update_time ', Time()); } returnParent::beforesave ($insert); }
3. Set Database Cache dependency:
Base basemodel.php for all table model inheritance
/ ** * @name Get Cache database Dependent * @author Testme * @date 2016-12-06 * @param array $params cache dependent parameters * @example * 1. Please check if the Model table has a update_time field * 2. Corresponding to use model please inherit Basemodel * 3. Call Basemodel's Getcachedbdependency () method */ Public Static functionGetcachedbdependency ($params= []) { //Cache Dependent SQL $DBDEPENDENCYSQL= Self::find ()->select (' Max (update_time) ') ->where (' Deleted=0 ') -CreateCommand ()-SQL; //Setting cache dependencies $dbDependency=Newdbdependency (); $dbDependency->db = Yii::$app->components[' DB ']; $dbDependency->sql =$DBDEPENDENCYSQL; $dbDependency->params =$params; return $dbDependency; }
4. Use when releasing the cache:
//Get Cache dependency $dbDependency= Syscodedetail::getcachedbdependency (); $cache= Yii::$app-Cache; //Update Cache files $result=$cache->set (' Syscodeenum ', Syscode::$_enum, 0,$dbDependency); if(!$result) { return false; }
Yii2.0 database caching relies on publication usage understanding