Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache doctrine "findOneBy()" query with cache id and cache lifetime option in Symfony 2.4?

I am working on the symfony 2.5 project with doctrine 2.4.

I want to cache query result with cache id and cache time, so I can delete the cache result, whenever needed though admin.

I am able to cache the query result with "createQueryBuilder()" option.

Example:

$this->createQueryBuilder('some_table')
                    ->select('some_table')
                    ->where('some_table.deleted_date IS NULL')
                    ->getQuery()
                    ->useResultCache(true)
                    ->setResultCacheLifetime(120) //Query Cache lifetime
                    ->setResultCacheId($queryCacheId) //Query Cache Id
                    ->getResult();

But I am not able to find the similar way to chache query result for "findOneBy()" option.

Example:

$this->findOneBy(array('some_field'=>$some_value));

I am looking some proper solution, any help is much appreciated.

like image 531
Yogesh Salvi Avatar asked Feb 23 '15 06:02

Yogesh Salvi


2 Answers

You need to redefine every findBy* or findOneBy* function into custom repository: this is the only way as doctrine2 default behaviour doesn't take into account this situation. Is up to you, unfortunately.

Also Ocramius (a Doctrine2 devel) say it here https://groups.google.com/d/msg/doctrine-user/RIeH8ZkKyEY/HnR7h2p0lCQJ

like image 171
DonCallisto Avatar answered Sep 28 '22 09:09

DonCallisto


Make a common function for this.

 $repo->findOneByYourSufff($yourStuff, $yourRepoClass);

Followed by your common function :

 public function findOneByYourSufff($yourStuff, $yourRepoClass) {


         $q = $this->createQueryBuilder()
                ->select('x.*')
                ->from($yourRepoClass, 'x');

                foreach($yourStuff as $fieldKey => $wh) {
                    $q->andWhere("b.$fieldKey = :fieldName");
                    $q->setParameter("fieldName", $wh);
                }

          $q->useResultCache(true)
                ->setResultCacheLifetime(120) //Query Cache lifetime
                ->setResultCacheId($queryCacheId) //Query Cache Id
                ->getSingleResult();

    return $q

 }
like image 27
Suf_Malek Avatar answered Sep 28 '22 09:09

Suf_Malek