Application of Yii cache dependency

Source: Internet
Author: User

Yii Cache relies on the application cache cache relies on Yii

Caching is a simple and effective way to improve the performance of your Web application. When we need to load the page too much time, for example, the query time is too long, or the call interface consumes too much I/O, the establishment of the cache is an effective method, it can avoid loading the page slow bad user experience. However, the data in the Web page is not static, it is changed, as the query has different conditions and different content, so the content of our cache will also change, this is the need for cache dependency.

setting up the cache

In general, we will set the expiration time for the cached variable, the expiration time, the variable will be valid, the next time the load will have to regenerate the cache, which is a dependency condition, set the expiration time.

// 变量将在30秒后失效Yii::app()->cache->set($id, $value, 30 ) ;        

The caching-dependent condition is not just so simple, it can depend on the file content, the database, the expression, the global variables in PHP.

Yii uses cache dependency

The above is my understanding in the work, I believe that we have to do static pages will also have this change in the way. Here's a description of the implementation (I'm using Yii1.1, as mentioned here):

1, Add the cache component to the application Config file components (component configuration).

' Components ' =>array (                    ...                     ' Cache '  => array  (                                                ' class '  =>  ' System.caching.CFileCache ',   #方式   file cache   Cache mode  [ cmemcache]:  use  PHP memcache  extensions. [capccache]:  use  PHP APC  extensions. etc., refer to the Yii community documentation for details.                                                                  ' Directorylevel '  => 2,                                                                 ),                      ...)

2. using cache dependency conditions

    • Dependent files

#依赖文件Yii::app()->cache->set($id, $value, 30, new CFileCacheDependency(‘FileName‘));

Depending on the file is also easy to understand, for example, the program will appear in the configuration of the city's storage files, may be a city or subordinate multiple zones, this file will change, the cached data should be based on dependency conditions expire, regenerate the cache file. The use of the method can be flexibly applied:

if(!Yii::app()->cache->get(‘city‘)){    Yii::app()->cache->set(‘city‘, include(‘path/city.php‘), 30, new CFileCacheDependency(‘path/city.php‘));}//todo:执行操作
    • Dependent SQL
      The broad use of SQL data should be a query dependent

#依赖SQLYii::app()->cache->set($id, $value, 30, new CDbCacheDependency(‘SELECT ...‘));

In a large amount of data in the order record in the statistical time period of the transaction amounts, as well as profits, in such a query page will produce too much load time, waiting is painful. We can store the results of the query to the cache in the time period, the order is changed, the time period of the statistic is related to today, then the statistic depends on the most recent creation time of the order, such as the creation time change, when the cache is invalidated, the cache can be regenerated, whereas the cache is not affected;

/* Order Form  id uerid price type (order type)  state (1 paid  0  not paid)  paytime   createtime isdelete*/#查询成交金额function  ordercheck ($starttime, $endtime) {   $ cacheid =  "Order". $starttime. $endtime;    //sets the Cache id     if ( ! Yii::app ()->cache->get ($cacheid)  ) {       $sql  =  "Select  sum (Price)   as sumprice FROM order WHERE  state=1 AND  Isdelete=0 ";        $addsql  = ";           if (  $starttime  )   $addsql. = " and createtime>={$starttime}";        if (  $endtime  )   $addsql. = " and createtime>={$ Endtime} ";       $res  = yii::app ()->createcommand ($sQL. $addsql)->queryall;        //start time or end time greater than or equal to today time stamp build dependency         $date  = date (' y-m-d ', Time ());        I F (  $starttime >=strtotime ($date)  | |   $endtime >=strtotime ($date)  ) {             //dependent conditions for the latest order time changes    $dependency  = new cdbcachedependency (' Select m AX (createtime)   from order where  state=1 and isdelete=0 ');           Yii::app ()->cache->set ($cacheid, $res [' Sumprice '] ,& nbsp;1800, $dependency);       }else{    Yii::app ()-&G T;cache->set ($cacheid,  $res [' Sumprice '], 1800];      }  }       Return yii::app ()->cache->get ($cacheid)  ;   } 
    • Dependency expressions

#表达式Yii::app()->cache->set($id, $value, 30, new CExpressionDependency(yii::app->session(‘automer‘)));

In the above example, when the global session Automer is changed, the corresponding cache is invalidated.
Other caches are no longer introduced, and I think it's important to understand the concepts of caching and caching dependencies
, write more application scenarios, you can design a practical caching program, which for the interface loading reaction time will improve a lot of speed. In the projects I've done, data is obtained through interfaces, and when writing a complex logic, it calls a lot of interfaces, very time-consuming, and there is no need to request the interface again by caching the data. A bit of a flaw is that the first load is time consuming, but it can be solved, if there is a script to update this cache, it is not a problem. There's more in-depth, cache-dependent management tools that will manage the generated cache for you, and here's a starting point, no more digging into it.

Yii also provides a lot of good caching methods, fragment caching, page caching, HTTP caching ...
Very good, on the basis of understanding the flexible application is also a great progress.

Come on, everybody, cheer yourself up, God!

Application of Yii cache dependency

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.