5

I want to invalidate the HTTP cache in symfony2. I use the following method:

protected function invalidateCache($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PURGE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $status == 200;
}

That works, no problem. But when I use a ESI include I with the controller() function (not path()) like:

{{ render_esi(controller('AcmeDemoBundle:Default:index')) }}

How do I get the url generated by the controller function? Or how can I invalidate the cached response of that esi request?

Tobias Nyholm
  • 1,142
  • 9
  • 16

1 Answers1

2

So here is how you do it: You don't.

The reason why I wanted to use the controller() function instead for path() is because Symfony will protect the URL from controller() from unauthorised requests. What you should do is to use path() and prefix the URLs with "esi/" and then protect that URL in your security.yml.

//app/config/security.yml
security: 
  # // ---
  access_control:
    - { path: ^/esi/.*, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 127.0.0.1 }

If you want to clear the cache you just use the url as you normally would.

Thank you @jongotlin on Twitter for helping me with this.

Tobias Nyholm
  • 1,142
  • 9
  • 16
  • 1
    Could you elaborate on thiws a bit more please. I am trying to invalidate my reverse proxy cache, but nothing is working so far. I wish to trigger the invalidation of the front page whenever a backend administrator accesses the backend. – Joe Yahchouchi Apr 16 '15 at 09:47
  • No, Sorry, but this is not the place how to describe the basics of cache invalidation. Make sure you read and understand this documentation http://symfony.com/doc/current/book/http_cache.html You should also consider using FOSHttpCacheBundle. Because they make stuff really easy. Read and understand their docs: http://foshttpcachebundle.readthedocs.org/en/latest/ – Tobias Nyholm Apr 16 '15 at 09:53
  • 1
    It's fine thank you. Shortly after writing this I understood my problem. The controller cannot access routes that need authentication, when I placed the things you mentioned in an unauthenticated route it worked (which was your answer anyway I think) – Joe Yahchouchi Apr 16 '15 at 10:00
  • My understanding of the reverse-proxy is that the PURGE method only deletes the cache for that url. So how does the esi/ url approach work? Would you be so kind as to share a snippet of your controller code for this? Thank you. – Acyra Feb 05 '17 at 12:07
  • You treat ESI request the same as any other URL. (You would not use the `controller()` function.) But, as I said, be aware that you have to protect your ESI endpoints with a firewall rule. – Tobias Nyholm Feb 06 '17 at 09:01