当我的Symfony2应用程序使用缓存时,何时不是?我怎么知道?

时间:2015-01-07 13:39:01

标签: php symfony caching memcached apc

拥有此实体:

/**
 * @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表的查询,这让我觉得没有使用缓存。

1 个答案:

答案 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 )