This tutorial is based on native doctrine/cache package. First of all, APC must be enabled in php.ini file. Example below will show us how to use APC cache to increase application performance. For more information, you can read Doctrine Caching chapter and Alternative PHP Cache.


Facts



Configurations


config_dev.yml


doctrine:
orm:
metadata_cache_driver:
type: apc
query_cache_driver:
type: apc
result_cache_driver:
type: apc

php.ini


extension=apc.so
apc.enabled=1
apc.shm_segments=1
apc.shm_size=32M
apc.cache_by_default=1
apc.stat=1
apc.rfc1867=1
apc.enable_cli=1

Testing


You can use browser based application APC-Admin to monitor caching activities.


Query base


public function findAll()
{
$qb = $this->createQueryBuilder('l')
->select('l, t, p')
->innerJoin('l.team', 't')
->innerJoin('t.player', 'p')
->orderBy('l.name', 'ASC')
->addOrderBy('t.name', 'ASC')
->addOrderBy('p.name', 'ASC')
->getQuery();

$qb = $qb->getResult();

return $qb;
}

You must add line below to the query to enable query caching.


...
->getQuery()
->useQueryCache(true);

You must add line below to the query to enable result caching.


...
->getQuery()
->useResultCache(true, 60, 'my_unique_cache_id');

No cache


Millisecond MB
2728 42.2 (*)
1050 28.5
650 28.5
664 28.5
669 28.5

Cached files: 0 KBytes
Cached variables: 0 KBytes
Cache variable name: NA

metadata_cache_driver enabled


Millisecond MB
3312 40.2 (*)
1462 28.2
698 28.2
670 28.2
681 28.2

Cached files: 9.2 KBytes
Cached variables: 9.2 KBytes
Cache variable names:
sf2orm_default_f2fbb5259b59469e8f50fbd0bfaef6747e168f1e5a445e5cb5812f652c835bf9[Application\BackendBundle\Entity\Player$CLASSMETADATA][1] (Expires: NA)

query_cache_driver enabled


Millisecond MB
3054 40.2 (*)
651 26.5
632 26.5
648 26.5
635 26.5

Cached files: 3.8 KBytes
Cached variables: 3.8 KBytes
Cache variable names:
sf2orm_default_f2fbb5259b59469e8f50fbd0bfaef6747e168f1e5a445e5cb5812f652c835bf9[07aa386f36aa0c503519f5baf6076bda][1] (Expires: NA)

result_cache_driver enabled


Millisecond MB
3301 40.8 (*)
646 28.8
642 28.8
696 28.8
627 28.8

Cached files: 346.8 KBytes
Cached variables: 346.8 KBytes
Cache variable names:
DoctrineNamespaceCacheKey[sf2orm_default_f2fbb5259b59469e8f50fbd0bfaef6747e168f1e5a445e5cb5812f652c835bf9] (Expires: never)
sf2orm_default_f2fbb5259b59469e8f50fbd0bfaef6747e168f1e5a445e5cb5812f652c835bf9[my_unique_cache_id][1] (Expires: 60 sec)

All three enabled


Millisecond MB
1854 41.0 (*)
628 26.8
636 26.8
632 26.8
622 26.8

Cached files: 358.5 KBytes
Cached variables: 358.5 KBytes
Cache variable names:
sf2orm_default_f2fbb5259b59469e8f50fbd0bfaef6747e168f1e5a445e5cb5812f652c835bf9[07aa386f36aa0c503519f5baf6076bda][1] (Expires: NA)