Here is an example of how you can cache results from a single repository for functions:
findOneBy(['foo' => 'bar'])findOneByFoo('bar')findOneBy(['bar' => 'foo', 'foo' => 'bar')- etc...
It overrides the function EntityRepository::FindOneBy . It follows the same signature, so there is no need to update the calling code. All calls of type FindOneBy% will go through our findOneBy implementation.
<?php namespace MyLib\Entity\Repository; use Doctrine\ORM\EntityRepository; class MyObjectRepository extends EntityRepository { const CACHE_KEY = 'my_object'; const ALIAS = 'my_object'; public function findOneBy(array $criteria, array $orderBy = null) { $queryBuilder = $this->createQueryBuilder(self::ALIAS); foreach($criteria as $field => $value) { $queryBuilder->andWhere(self::ALIAS . ".{$field} = :{$field}")->setParameter($field, $value); } if (is_array($orderBy)) { foreach ($orderBy as $field => $dir) { $queryBuilder->addOrderBy($field, $dir); } } $queryBuilder->setMaxResults(1); $query = $queryBuilder->getQuery(); $query->useResultCache(true, 3600, self::CACHE_KEY); $result = $query->getResult(); if ($result) return reset($result); return $result; } public function findAll() { $query = $this->getEntityManager()->createQuery('select v from \OAS\Entity\MyObject v'); $query->useResultCache(true, 3600, self::CACHE_KEY); $result = $query->getResult(); return $result; } public function invalidateCache() {
This can be done, for example, in a more OOP style, expanding the intermediate class if you want to say that it has a property in the repository that just turned on or off the cache. You can extend a similar approach for other operations with repository operations.
source share