Summary of Common Cache Application Examples of Yii Framework

  • 2021-12-21 04:22:22
  • OfStack

In this paper, examples are given to describe the common caching applications of Yii framework. Share it for your reference, as follows:

1 First, you need to install apc or memcache or redis. After installation. Take redis as an example. As for how to install, find more Du Niang.

Add components in the configuration file as follows.


'cache'=>array(
  'class'=>'core.extensions.redis.Predis',
     'class'=>'core.extensions.redis.CRedisCache',
     'servers'=>array(
      array(
        'host'=>'192.168.1.xx',
        'port'=>6379,
       ),
      ),
    ),

2 The simplest example. set get.


Yii::app()->cache->set('id', date("Y-m-d H:i:s"), 5); // Set the valid time to 5.
echo Yii::app()->cache->get("id")."<br/>";
sleep(2);
echo Yii::app()->cache->get("id"); // Within the validity period of cache   Data will be output 
sleep(4);
echo Yii::app()->cache->get("id"); // Cache failure, output is empty 

3 database query cache.


//3.1  The simplest database cache. 
$sql = 'select * from {{settings}}';
$cmd = Yii::app()->db->cache(10, null)->createCommand($sql);
$rows = $cmd->queryAll();
//3.2  Plus 1 The concept of cache dependency. 
$dp_sql = "SELECT MAX(id) FROM plat2_settings ";
$dependency = new CDbCacheDependency( $dp_sql );
$sql  = "SELECT * FROM `plat2_settings`";
$rows = Yii::app()->db->cache(1000, $dependency)->createCommand($sql)->queryAll();

The above code means that when querying the corresponding data, it will first judge whether the result data depending on the query SELECT MAX (id) FROM plat2_settings is updated.

If there is an update, re-query the data, and if the dependence is not updated, directly adjust the cached data. After 1000 seconds, the query will be re-checked.

4 fragment cache.


if($this->beginCache("xx"))
{
  echo "test cache ";
  $this->endCache();
}
//beginCache  There will be the first 2 Parameters, meaning that the specified buffer is selected. If you need to use different caches, you can customize them. 

5 page cache.


public function filters(){
  return array(
    array(
      'COutputCache+index+admin',
      'duration' => 120,
      'varyByParam'=>array('id'),
    ),
  );
}

Using the controller, the specified action is cached directly.

There is also varyBySession to choose from.

More readers interested in Yii can check the topics of this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Yii framework.


Related articles: