Created
February 21, 2017 16:21
-
-
Save sryabov/eff5251a6ccb26d32b557dcea979c1ce to your computer and use it in GitHub Desktop.
Universal caching Repository for Symfony
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace BlogBundle\Entity\Repository; | |
use Doctrine\ORM\EntityRepository; | |
class CachedDirectoryRepository extends EntityRepository | |
{ | |
const CACHE_TIME = 3600; // 60 * 60 | |
/** | |
* Prepare cached query for findBy and findByOne | |
* | |
* @param array $criteria | |
* @param array $orderBy | |
* @param integer $limit | |
* @param integer $offset | |
* | |
* @return \Doctrine\ORM\Query | |
*/ | |
protected function makeFindByCachedQuery(array $criteria, array $orderBy = null, $limit = null, $offset = null) | |
{ | |
$qb = $this->createQueryBuilder('e'); | |
if ($criteria) { | |
foreach ($criteria as $field => $value) { | |
if (is_array($value)) { | |
$where = sprintf('e.%1$s IN :%1$s', $field); | |
if (array_search(null, $value, true) !== false) { | |
$where = sprintf('(%s OR e.%s IS NULL)', $where, $field); | |
} | |
} elseif (is_null($value)) { | |
$where = sprintf('e.%s IS NULL', $field); | |
} else { | |
$where = sprintf('e.%1$s = :%1$s', $field); | |
} | |
$qb->andWhere($where); | |
if (!is_null($value)) { | |
$qb->setParameter($field, $value); | |
} | |
} | |
} | |
if ($orderBy) { | |
foreach ($orderBy as $field => $dir) { | |
$qb->addOrderBy(sprintf('e.%s', $field), $dir); | |
} | |
} | |
$qb->setMaxResults($limit); | |
$qb->setFirstResult($offset); | |
return $qb->getQuery()->useResultCache(true, static::CACHE_TIME); | |
} | |
/** | |
* {@inderitDoc} | |
*/ | |
public function findOneBy(array $criteria, array $orderBy = null) | |
{ | |
return $this->makeFindByCachedQuery($criteria, $orderBy, 1, 0)->getOneOrNullResult(); | |
} | |
/** | |
* {@inderitDoc} | |
*/ | |
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) | |
{ | |
return $this->makeFindByCachedQuery($criteria, $orderBy, $limit, $offset)->getResult(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment