大佬教程收集整理的这篇文章主要介绍了php – Doctrine 2和ORM:如何缓存某个实体的每个查询?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Entitymanager; use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\ArrayCache; class MyBaseRepo extends EntityRepository { public function __construct(Entitymanager $entitymanager) { parent::__construct($entitymanager); $cache = $em->getConfiguration()->getHydrationCache(); $this->cache = $cache ?: new ArrayCache(); } public function find($id) { if (!$object = $this->tryFetchFromCache($id)) { $object = parent::find($id); $this->cache->save($this->generateKey($id),$object); } return $object; } protected function tryFetchFromCache($id) { if (!$object = $this->cache->fetch($this->generateCacheKey($id))) { return null; } return $this->getEntitymanager()->merge($object); } public function generateCacheKey($id) { /* ... */ } }@H_772_1@在引导应用程序时,您可以强制将其作为配置中ORM的基本存储库:
$configuration = new \Doctrine\ORM\Configuration(); $configuration->setDefaultRepositoryClassName('My\MyBaseRepo');@H_772_1@当您的任何实体发生更新/保存时,这也会强制您清除缓存条目:
use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Event\OnFlushEventArgs; use Doctrine\ORM\Events; class IssueupdateSubscriber implements EventSubscriber { public function onFlush(OnFlushEventArgs $args) { $em = $args->getEntitymanager(); $uow = $em->getUnitOfWork(); if (!$cache = $em->getConfiguration()->getHydrationCache()) { return; } $busted = array_merge( $uow->getscheduledEntityupdates(),$uow->getscheduledEntitydeletions(),); foreach ($busted as $entityToClear) { $className = get_class($entityToClear); $Metadata = $em->getClassMetadata($className); $repository = $em->getRepository($className); $id = $Metadata->getIdentifierValues($entityToClear); $cache->delete($repository->generateCacheKey($id)); } } public function getSubscribedEvents() { return array(Events::onFlush); } }@H_772_1@请注意,此实现不会拦截对给定实体的数据库的所有访问.它不会拦截由代理引起的延迟加载初始化,而且它非常脆弱,所以请设置一些适当的集成测试来支持它.
以上是大佬教程为你收集整理的php – Doctrine 2和ORM:如何缓存某个实体的每个查询?全部内容,希望文章能够帮你解决php – Doctrine 2和ORM:如何缓存某个实体的每个查询?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。