Special Topics - Setting Up Database Requests Caching

Caching is a cheap and effective way to improve the performance of your Web applications. By storing relatively static data in cache and serving it from cache when requested, you can save the time needed to generate the data and improve effectivity of your scripts.

Using cache in ApPHP Framework mainly involves first of all a right configuring of using cache mechanism. The following configuration specifies the cache settings (by default cache is turned off).

// Cache settings 
'cache' => array(
    'enable' => true,
    'type' => 'auto', 			/* 'auto' or 'manual' */
    'lifetime' => 20,  			/* in minutes */
    'path' => 'protected/tmp/cache/'

Cache mechanism is embedded in Directy CMF and you may see the current state of your cache settings in Backend panel.

When the application is running, the cache file is created in specified directory and then used for next access of this data. Cache can be used only for read requests (SELECT), because only the requests of this type generate a result. Write requests (INSERT, UPDATE, etc.) can not be cached by the system because they don't generate any result.

Each SELECT request gets from the system a unique identifier, but sometimes it's impossible for some reasons (for example when you use a dinamic parameters in each request). For such cases you may define a special identifier manually (see cacheId parameter in example below).
$news = News::model()->findAll(
        'condition'=>'is_published = :isPublished AND created_at < :currentDate',
        'order'=>'created_at DESC',
        'limit'=>'0, '.(int)$newsCount,

To enable/disable manually caching you may use following methods: $this->_db->cacheOn(); and $this->_db->cacheOff();. This can be useful if you want to keep certain queries from being cached directly in models, for example:
// Turn caching on
$result = $this->_db->select('SELECT * FROM one_table');

// Turn caching off for this one query
$result = $this->_db->select('SELECT * FROM one_table');

// Turn caching back on
$result = $this->_db->select('SELECT * FROM another_table');

To run caching autonatically use 'type' => 'auto' settings, run cache manually fo specific queries only use 'type' => 'manual'