拥有此实体:
/**
* @ORM\Entity
* @ORM\Table(name="nomencladores.pais", schema="nomencladores")
* @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\PaisRepository")
* @UniqueEntity(fields={"nombre"}, message="El pais ya existe en nuestra base de datos")
*/
class Pais
{
use IdentifierAutogeneratedEntityTrait;
use NamedEntityTrait;
use ActiveEntityTrait;
}
这个知识库:
class PaisRepository extends EntityRepository
{
public function getPaises()
{
$qb = $this->createQueryBuilder('pais');
$query = $qb->getQuery();
$query->useResultCache(true, 3600, 'paises_cache');
return $query->getResult();
}
}
在我的控制器上执行此调用:
/**
* @Route("/paises", name="paises")
* @Method("GET")
*/
public function getPaisAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AppBundle:Pais')->getPaises();
$response['message'] = "";
$response['entities'] = [];
if (!$entities) {
$response['message'] = "No se encontraron países";
}
foreach ($entities as $pais) {
$paises = array();
$paises['id'] = $pais->getId();
$paises['text'] = $pais->getNombre();
$response['entities'][] = $paises;
}
return new JsonResponse($response);
}
在config_prod.yml
档案中显示:
doctrine:
orm:
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
我如何知道我的应用是使用缓存结果还是一直在进行数据库查询?我正在查看Symfony2工具栏(因为我在开发环境中执行测试),并且我一直看到paises
表的查询,这让我觉得没有使用缓存。
答案 0 :(得分:1)
我相信您必须告诉Doctrine何时使用配置的缓存驱动程序,如下所示:
public function getSomeEntities()
{
$qb = $this->createQueryBuilder('a');
$qb
->where('a.title = "test article"')
->orderBy('id', 'ASC')
;
$query = $qb->getQuery();
$query->useResultCache(true, 60, 'uniqueCacheId');
return $query->getResult();
}
您还可以指定查询缓存的使用:
$query->useQueryCache(true);
您可以在Doctrine\ORM\Query class documentation中看到useQueryCache
函数接受单个布尔参数,useResultCache
具有以下参数:
useResultCache( boolean $bool, integer $timeToLive = null, string $resultCacheId = null )