0

I have the following action in my controller :

public function popularPlacesAction()
{
    $em = $this->getDoctrine()->getManager();

    $query = $em->createQuery(
        "SELECT COUNT(s.id) as total, l.city as name, l.country_code as country_code
          FROM AcmeMyBundle:Sample s 
          LEFT JOIN s.location l 
          WHERE l.city != ''
          GROUP BY name
          ORDER BY total DESC"
    )->setMaxResults(15);

    $cities = $query->getResult();

    return array(
        'cities' => $cities
    );
}

I want to use cache to set an expiration date for the response, don't matter if the result of the query have changed. I just want to set the response as public and refresh the response every hour for exemple. How to accomplish this without performing the doctrine query when the response come from the cache ?

1 Answer 1

3

You need to use some caching method (maybe Varnish or symfony's reverse proxy), and then set some caching headers to your action response. Have a look here: Expiration with the Cache-Control Header ex:

public function popularPlacesAction()
{
    ... 
    $response = new Response();
    $response->setSharedMaxAge(3600);
    $response->setContent(....);
    return $response;
}

Hope this helps. Other docs to read: HTTP Cache

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. The thing I don't understand about this is : where to put this snippet in my action if I want to execute the doctrine query only when the cached response has expired ?
@YvanL you don't have to. A reverse proxy (like varnish) won't make another request to your app if it still has a fresh response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.