caching.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. Caching
  2. =======
  3. Doctrine provides cache drivers in the ``Common`` package for some
  4. of the most popular caching implementations such as APC, Memcache
  5. and Xcache. We also provide an ``ArrayCache`` driver which stores
  6. the data in a PHP array. Obviously, the cache does not live between
  7. requests but this is useful for testing in a development
  8. environment.
  9. Cache Drivers
  10. -------------
  11. The cache drivers follow a simple interface that is defined in
  12. ``Doctrine\Common\Cache\Cache``. All the cache drivers extend a
  13. base class ``Doctrine\Common\Cache\AbstractCache`` which implements
  14. the before mentioned interface.
  15. The interface defines the following methods for you to publicly
  16. use.
  17. - fetch($id) - Fetches an entry from the cache.
  18. - contains($id) - Test if an entry exists in the cache.
  19. - save($id, $data, $lifeTime = false) - Puts data into the cache.
  20. - delete($id) - Deletes a cache entry.
  21. Each driver extends the ``AbstractCache`` class which defines a few
  22. abstract protected methods that each of the drivers must
  23. implement.
  24. - \_doFetch($id)
  25. - \_doContains($id)
  26. - \_doSave($id, $data, $lifeTime = false)
  27. - \_doDelete($id)
  28. The public methods ``fetch()``, ``contains()``, etc. utilize the
  29. above protected methods that are implemented by the drivers. The
  30. code is organized this way so that the protected methods in the
  31. drivers do the raw interaction with the cache implementation and
  32. the ``AbstractCache`` can build custom functionality on top of
  33. these methods.
  34. APC
  35. ~~~
  36. In order to use the APC cache driver you must have it compiled and
  37. enabled in your php.ini. You can read about APC
  38. `in the PHP Documentation <http://us2.php.net/apc>`_. It will give
  39. you a little background information about what it is and how you
  40. can use it as well as how to install it.
  41. Below is a simple example of how you could use the APC cache driver
  42. by itself.
  43. .. code-block:: php
  44. <?php
  45. $cacheDriver = new \Doctrine\Common\Cache\ApcCache();
  46. $cacheDriver->save('cache_id', 'my_data');
  47. Memcache
  48. ~~~~~~~~
  49. In order to use the Memcache cache driver you must have it compiled
  50. and enabled in your php.ini. You can read about Memcache
  51. ` on the PHP website <http://us2.php.net/memcache>`_. It will
  52. give you a little background information about what it is and how
  53. you can use it as well as how to install it.
  54. Below is a simple example of how you could use the Memcache cache
  55. driver by itself.
  56. .. code-block:: php
  57. <?php
  58. $memcache = new Memcache();
  59. $memcache->connect('memcache_host', 11211);
  60. $cacheDriver = new \Doctrine\Common\Cache\MemcacheCache();
  61. $cacheDriver->setMemcache($memcache);
  62. $cacheDriver->save('cache_id', 'my_data');
  63. Xcache
  64. ~~~~~~
  65. In order to use the Xcache cache driver you must have it compiled
  66. and enabled in your php.ini. You can read about Xcache
  67. `here <http://xcache.lighttpd.net/>`_. It will give you a little
  68. background information about what it is and how you can use it as
  69. well as how to install it.
  70. Below is a simple example of how you could use the Xcache cache
  71. driver by itself.
  72. .. code-block:: php
  73. <?php
  74. $cacheDriver = new \Doctrine\Common\Cache\XcacheCache();
  75. $cacheDriver->save('cache_id', 'my_data');
  76. Redis
  77. ~~~~~
  78. In order to use the Redis cache driver you must have it compiled
  79. and enabled in your php.ini. You can read about what is Redis
  80. `from here <http://redis.io/>`_. Also check
  81. `A PHP extension for Redis <https://github.com/nicolasff/phpredis/>`_ for how you can use
  82. and install Redis PHP extension.
  83. Below is a simple example of how you could use the Redis cache
  84. driver by itself.
  85. .. code-block:: php
  86. <?php
  87. $redis = new Redis();
  88. $redis->connect('redis_host', 6379);
  89. $cacheDriver = new \Doctrine\Common\Cache\RedisCache();
  90. $cacheDriver->setRedis($redis);
  91. $cacheDriver->save('cache_id', 'my_data');
  92. Using Cache Drivers
  93. -------------------
  94. In this section we'll describe how you can fully utilize the API of
  95. the cache drivers to save cache, check if some cache exists, fetch
  96. the cached data and delete the cached data. We'll use the
  97. ``ArrayCache`` implementation as our example here.
  98. .. code-block:: php
  99. <?php
  100. $cacheDriver = new \Doctrine\Common\Cache\ArrayCache();
  101. Saving
  102. ~~~~~~
  103. To save some data to the cache driver it is as simple as using the
  104. ``save()`` method.
  105. .. code-block:: php
  106. <?php
  107. $cacheDriver->save('cache_id', 'my_data');
  108. The ``save()`` method accepts three arguments which are described
  109. below.
  110. - ``$id`` - The cache id
  111. - ``$data`` - The cache entry/data.
  112. - ``$lifeTime`` - The lifetime. If != false, sets a specific
  113. lifetime for this cache entry (null => infinite lifeTime).
  114. You can save any type of data whether it be a string, array,
  115. object, etc.
  116. .. code-block:: php
  117. <?php
  118. $array = array(
  119. 'key1' => 'value1',
  120. 'key2' => 'value2'
  121. );
  122. $cacheDriver->save('my_array', $array);
  123. Checking
  124. ~~~~~~~~
  125. Checking whether some cache exists is very simple, just use the
  126. ``contains()`` method. It accepts a single argument which is the ID
  127. of the cache entry.
  128. .. code-block:: php
  129. <?php
  130. if ($cacheDriver->contains('cache_id')) {
  131. echo 'cache exists';
  132. } else {
  133. echo 'cache does not exist';
  134. }
  135. Fetching
  136. ~~~~~~~~
  137. Now if you want to retrieve some cache entry you can use the
  138. ``fetch()`` method. It also accepts a single argument just like
  139. ``contains()`` which is the ID of the cache entry.
  140. .. code-block:: php
  141. <?php
  142. $array = $cacheDriver->fetch('my_array');
  143. Deleting
  144. ~~~~~~~~
  145. As you might guess, deleting is just as easy as saving, checking
  146. and fetching. We have a few ways to delete cache entries. You can
  147. delete by an individual ID, regular expression, prefix, suffix or
  148. you can delete all entries.
  149. By Cache ID
  150. ^^^^^^^^^^^
  151. .. code-block:: php
  152. <?php
  153. $cacheDriver->delete('my_array');
  154. All
  155. ^^^
  156. If you simply want to delete all cache entries you can do so with
  157. the ``deleteAll()`` method.
  158. .. code-block:: php
  159. <?php
  160. $deleted = $cacheDriver->deleteAll();
  161. Namespaces
  162. ~~~~~~~~~~
  163. If you heavily use caching in your application and utilize it in
  164. multiple parts of your application, or use it in different
  165. applications on the same server you may have issues with cache
  166. naming collisions. This can be worked around by using namespaces.
  167. You can set the namespace a cache driver should use by using the
  168. ``setNamespace()`` method.
  169. .. code-block:: php
  170. <?php
  171. $cacheDriver->setNamespace('my_namespace_');
  172. Integrating with the ORM
  173. ------------------------
  174. The Doctrine ORM package is tightly integrated with the cache
  175. drivers to allow you to improve performance of various aspects of
  176. Doctrine by just simply making some additional configurations and
  177. method calls.
  178. Query Cache
  179. ~~~~~~~~~~~
  180. It is highly recommended that in a production environment you cache
  181. the transformation of a DQL query to its SQL counterpart. It
  182. doesn't make sense to do this parsing multiple times as it doesn't
  183. change unless you alter the DQL query.
  184. This can be done by configuring the query cache implementation to
  185. use on your ORM configuration.
  186. .. code-block:: php
  187. <?php
  188. $config = new \Doctrine\ORM\Configuration();
  189. $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ApcCache());
  190. Result Cache
  191. ~~~~~~~~~~~~
  192. The result cache can be used to cache the results of your queries
  193. so that we don't have to query the database or hydrate the data
  194. again after the first time. You just need to configure the result
  195. cache implementation.
  196. .. code-block:: php
  197. <?php
  198. $config->setResultCacheImpl(new \Doctrine\Common\Cache\ApcCache());
  199. Now when you're executing DQL queries you can configure them to use
  200. the result cache.
  201. .. code-block:: php
  202. <?php
  203. $query = $em->createQuery('select u from \Entities\User u');
  204. $query->useResultCache(true);
  205. You can also configure an individual query to use a different
  206. result cache driver.
  207. .. code-block:: php
  208. <?php
  209. $query->setResultCacheDriver(new \Doctrine\Common\Cache\ApcCache());
  210. .. note::
  211. Setting the result cache driver on the query will
  212. automatically enable the result cache for the query. If you want to
  213. disable it pass false to ``useResultCache()``.
  214. ::
  215. <?php
  216. $query->useResultCache(false);
  217. If you want to set the time the cache has to live you can use the
  218. ``setResultCacheLifetime()`` method.
  219. .. code-block:: php
  220. <?php
  221. $query->setResultCacheLifetime(3600);
  222. The ID used to store the result set cache is a hash which is
  223. automatically generated for you if you don't set a custom ID
  224. yourself with the ``setResultCacheId()`` method.
  225. .. code-block:: php
  226. <?php
  227. $query->setResultCacheId('my_custom_id');
  228. You can also set the lifetime and cache ID by passing the values as
  229. the second and third argument to ``useResultCache()``.
  230. .. code-block:: php
  231. <?php
  232. $query->useResultCache(true, 3600, 'my_custom_id');
  233. Metadata Cache
  234. ~~~~~~~~~~~~~~
  235. Your class metadata can be parsed from a few different sources like
  236. YAML, XML, Annotations, etc. Instead of parsing this information on
  237. each request we should cache it using one of the cache drivers.
  238. Just like the query and result cache we need to configure it
  239. first.
  240. .. code-block:: php
  241. <?php
  242. $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcCache());
  243. Now the metadata information will only be parsed once and stored in
  244. the cache driver.
  245. Clearing the Cache
  246. ------------------
  247. We've already shown you previously how you can use the API of the
  248. cache drivers to manually delete cache entries. For your
  249. convenience we offer a command line task for you to help you with
  250. clearing the query, result and metadata cache.
  251. From the Doctrine command line you can run the following command.
  252. .. code-block:: php
  253. $ ./doctrine clear-cache
  254. Running this task with no arguments will clear all the cache for
  255. all the configured drivers. If you want to be more specific about
  256. what you clear you can use the following options.
  257. To clear the query cache use the ``--query`` option.
  258. .. code-block:: php
  259. $ ./doctrine clear-cache --query
  260. To clear the metadata cache use the ``--metadata`` option.
  261. .. code-block:: php
  262. $ ./doctrine clear-cache --metadata
  263. To clear the result cache use the ``--result`` option.
  264. .. code-block:: php
  265. $ ./doctrine clear-cache --result
  266. When you use the ``--result`` option you can use some other options
  267. to be more specific about what queries result sets you want to
  268. clear.
  269. Just like the API of the cache drivers you can clear based on an
  270. ID, regular expression, prefix or suffix.
  271. .. code-block:: php
  272. $ ./doctrine clear-cache --result --id=cache_id
  273. Or if you want to clear based on a regular expressions.
  274. .. code-block:: php
  275. $ ./doctrine clear-cache --result --regex=users_.*
  276. Or with a prefix.
  277. .. code-block:: php
  278. $ ./doctrine clear-cache --result --prefix=users_
  279. And finally with a suffix.
  280. .. code-block:: php
  281. $ ./doctrine clear-cache --result --suffix=_my_account
  282. .. note::
  283. Using the ``--id``, ``--regex``, etc. options with the
  284. ``--query`` and ``--metadata`` are not allowed as it is not
  285. necessary to be specific about what you clear. You only ever need
  286. to completely clear the cache to remove stale entries.
  287. Cache Slams
  288. -----------
  289. Something to be careful of when utilizing the cache drivers is
  290. cache slams. If you have a heavily trafficked website with some
  291. code that checks for the existence of a cache record and if it does
  292. not exist it generates the information and saves it to the cache.
  293. Now if 100 requests were issued all at the same time and each one
  294. sees the cache does not exist and they all try and insert the same
  295. cache entry it could lock up APC, Xcache, etc. and cause problems.
  296. Ways exist to work around this, like pre-populating your cache and
  297. not letting your users requests populate the cache.
  298. You can read more about cache slams
  299. `in this blog post <http://notmysock.org/blog/php/user-cache-timebomb.html>`_.