caching.rst 1.88 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Caching
=======

A ``Doctrine\DBAL\Statement`` can automatically cache result sets.

For this to work an instance of ``Doctrine\Common\Cache\Cache`` must be provided.
This can be set on the configuration object (optionally it can also be passed at query time):

::

    <?php
    $cache = new \Doctrine\Common\Cache\ArrayCache();
    $config = $conn->getConfiguration();
    $config->setResultCacheImpl($cache);

To get the result set of a query cached it is necessary to pass a
``Doctrine\DBAL\Cache\QueryCacheProfile`` instance to the ``executeQuery`` or ``executeCacheQuery``
instance. The difference between these two methods is that the former does not
require this instance, while the later has this instance as a required parameter:

::

    <?php
    $stmt = $conn->executeQuery($query, $params, $types, new QueryCacheProfile(0, "some key"));
Tom Graham's avatar
Tom Graham committed
25
    $stmt = $conn->executeCacheQuery($query, $params, $types, new QueryCacheProfile(0, "some key"));
26

Phil Davis's avatar
Phil Davis committed
27
It is also possible to pass in a ``Doctrine\Common\Cache\Cache`` instance into the
28 29 30 31 32 33 34 35 36 37
constructor of ``Doctrine\DBAL\Cache\QueryCacheProfile`` in which case it overrides
the default cache instance:

::

    <?php
    $cache = new \Doctrine\Common\Cache\FilesystemCache(__DIR__);
    new QueryCacheProfile(0, "some key", $cache);

In order for the data to actually be cached its necessary to ensure that the entire
Phil Davis's avatar
Phil Davis committed
38
result set is read (the easiest way to ensure this is to use ``fetchAll``) and the statement
39 40 41 42 43
object is closed:

::

    <?php
Tom Graham's avatar
Tom Graham committed
44
    $stmt = $conn->executeCacheQuery($query, $params, $types, new QueryCacheProfile(0, "some key"));
45
    $data = $stmt->fetchAll();
Jon Langevin's avatar
Jon Langevin committed
46
    $stmt->closeCursor(); // at this point the result is cached
47 48 49

.. warning::

50
    When using the cache layer not all fetch modes are supported. See the code of the `ResultCacheStatement <https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Cache/ResultCacheStatement.php>`_ for details.