caching.md 7.7 KB
Newer Older
Alexander Makarov committed
1 2 3
Caching
=======

resurtm committed
4 5 6 7 8 9 10 11
Overview and Base Concepts
--------------------------

Caching is a cheap and effective way to improve the performance of a web application. By storing relatively
static data in cache and serving it from cache when requested, we save the time needed to generate the data.

Using cache in Yii mainly involves configuring and accessing a cache application component. The following
application configuration specifies a cache component that uses [memcached](http://memcached.org/) with
resurtm committed
12 13
two cache servers. Note, this configuration should be done in file located at `@app/config/web.php` alias
in case you're using basic sample application.
resurtm committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

```php
'components' => array(
	'cache' => array(
		'class' => '\yii\caching\MemCache',
		'servers' => array(
			array(
				'host' => 'server1',
				'port' => 11211,
				'weight' => 100,
			),
			array(
				'host' => 'server2',
				'port' => 11211,
				'weight' => 50,
			),
		),
	),
),
```

When the application is running, the cache component can be accessed through `Yii::$app->cache` call.

resurtm committed
37 38
Yii provides various cache components that can store cached data in different media. The following
is a summary of the available cache components:
resurtm committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52

* [[\yii\caching\ApcCache]]: uses PHP [APC](http://php.net/manual/en/book.apc.php) extension. This option can be
  considered as the fastest one when dealing with cache for a centralized thick application (e.g. one
  server, no dedicated load balancers, etc.).

* [[\yii\caching\DbCache]]: uses a database table to store cached data. By default, it will create and use a
  [SQLite3](http://sqlite.org/) database under the runtime directory. You can explicitly specify a database for
  it to use by setting its `db` property.

* [[\yii\caching\DummyCache]]: presents dummy cache that does no caching at all. The purpose of this component
  is to simplify the code that needs to check the availability of cache. For example, during development or if
  the server doesn't have actual cache support, we can use this cache component. When an actual cache support
  is enabled, we can switch to use the corresponding cache component. In both cases, we can use the same
  code `Yii::$app->cache->get($key)` to attempt retrieving a piece of data without worrying that
Carsten Brandt committed
53
  `Yii::$app->cache` might be `null`.
resurtm committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

* [[\yii\caching\FileCache]]: uses standard files to store cached data. This is particular suitable
  to cache large chunk of data (such as pages).

* [[\yii\caching\MemCache]]: uses PHP [memcache](http://php.net/manual/en/book.memcache.php)
  and [memcached](http://php.net/manual/en/book.memcached.php) extensions. This option can be considered as
  the fastest one when dealing with cache in a distributed applications (e.g. with several servers, load
  balancers, etc.)

* [[\yii\caching\RedisCache]]: implements a cache component based on [Redis](http://redis.io/) NoSQL database.

* [[\yii\caching\WinCache]]: uses PHP [WinCache](http://iis.net/downloads/microsoft/wincache-extension)
  ([see also](http://php.net/manual/en/book.wincache.php)) extension.

* [[\yii\caching\XCache]]: uses PHP [XCache](http://xcache.lighttpd.net/) extension.

* [[\yii\caching\ZendDataCache]]: uses
  [Zend Data Cache](http://files.zend.com/help/Zend-Server-6/zend-server.htm#data_cache_component.htm)
  as the underlying caching medium.

Tip: because all these cache components extend from the same base class [[Cache]], one can switch to use
a different type of cache without modifying the code that uses cache.

Caching can be used at different levels. At the lowest level, we use cache to store a single piece of data,
such as a variable, and we call this data caching. At the next level, we store in cache a page fragment which
is generated by a portion of a view script. And at the highest level, we store a whole page in cache and serve
it from cache as needed.

In the next few subsections, we elaborate how to use cache at these levels.

Note, by definition, cache is a volatile storage medium. It does not ensure the existence of the cached
data even if it does not expire. Therefore, do not use cache as a persistent storage (e.g. do not use cache
to store session data or other valuable information).

Data Caching
------------

Data caching is about storing some PHP variable in cache and retrieving it later from cache. For this purpose,
the cache component base class [[\yii\caching\Cache]] provides two methods that are used most of the time:
[[set()]] and [[get()]]. Note, only serializable variables and objects could be cached successfully.

To store a variable `$value` in cache, we choose a unique `$key` and call [[set()]] to store it:

```php
Yii::$app->cache->set($key, $value);
```

The cached data will remain in the cache forever unless it is removed because of some caching policy
(e.g. caching space is full and the oldest data are removed). To change this behavior, we can also supply
an expiration parameter when calling [[set()]] so that the data will be removed from the cache after
a certain period of time:

```php
// keep the value in cache for at most 45 seconds
Yii::$app->cache->set($key, $value, 45);
```

Later when we need to access this variable (in either the same or a different web request), we call [[get()]]
with the key to retrieve it from cache. If the value returned is `false`, it means the value is not available
in cache and we should regenerate it:

```php
public function getCachedData()
{
	$key = /* generate unique key here */;
	$value = Yii::$app->getCache()->get($key);
	if ($value === false) {
		$value = /* regenerate value because it is not found in cache and then save it in cache for later use */;
lancecoder committed
122
		Yii::$app->cache->set($key, $value);
resurtm committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	}
	return $value;
}
```

This is the common pattern of arbitrary data caching for general use.

When choosing the key for a variable to be cached, make sure the key is unique among all other variables that
may be cached in the application. It is **NOT** required that the key is unique across applications because
the cache component is intelligent enough to differentiate keys for different applications.

Some cache storages, such as MemCache, APC, support retrieving multiple cached values in a batch mode,
which may reduce the overhead involved in retrieving cached data. A method named [[mget()]] is provided
to exploit this feature. In case the underlying cache storage does not support this feature,
[[mget()]] will still simulate it.

To remove a cached value from cache, call [[delete()]]; and to remove everything from cache, call [[flush()]].
Be very careful when calling [[flush()]] because it also removes cached data that are from other applications.

resurtm committed
142
Note, because [[Cache]] implements `ArrayAccess`, a cache component can be used liked an array. The followings
resurtm committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
are some examples:

```php
$cache = Yii::$app->getComponent('cache');
$cache['var1'] = $value1;  // equivalent to: $cache->set('var1', $value1);
$value2 = $cache['var2'];  // equivalent to: $value2 = $cache->get('var2');
```

### Cache Dependency

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.data#cache-dependency

### Query Caching

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.data#query-caching

Fragment Caching
----------------

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.fragment

### Caching Options

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.fragment#caching-options

### Nested Caching

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.fragment#nested-caching

Dynamic Content
---------------

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.dynamic

Page Caching
------------

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.page

### Output Caching

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.page#output-caching

### HTTP Caching

TBD: http://www.yiiframework.com/doc/guide/1.1/en/caching.page#http-caching