Symfony2: ESI setMaxAge Cache

2019-05-27 02:51发布

I have a Controller whose Action is rendered in twig with

{{ render_esi(controller('MyWebsiteBundle:Element:header')) }}

The Action itself looks like this:

/**
     * @return Response
     */
    public function headerAction()
    {
        $currentLocale = $this->getCurrentLocale();

        $response = $this->render('MyWebsiteBundle:Element:header.html.twig', array(
            'currentLocale' => $currentLocale,
            'myTime' => time()
        ));
        $response->setPublic();
        $response->setSharedMaxAge(3600);

        return $response;
    }

When I reload my Browser, the "myTime" changes everytime.

How can I use setShardeMaxAge(), so that the Twig is only renderd after the MaxAge is expired?

1条回答
再贱就再见
2楼-- · 2019-05-27 03:23

In Symfony2 there's a few things you need to do in order to activate esi caching.

1) In app/config/config.yml make sure you activated esi, with a fragments path.

framework:
    esi: { enabled: true }
    fragments: { path: /_proxy }

2) Wrap the kernel with the AppCache object

// web/app.php
$kernel = new AppCache($kernel); 

3) Set up the AppCache configuration

// app/AppCache.php
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;

class AppCache extends HttpCache
{
    protected function getOptions()
    {
        return array(
            'debug'                  => false,
            'default_ttl'            => 0,
            'private_headers'        => array('Authorization', 'Cookie'),
            'allow_reload'           => false,
            'allow_revalidate'       => false,
            'stale_while_revalidate' => 2,
            'stale_if_error'         => 60,
        );
    }
}

About your issue if it is caching your response and the only problem is that it's reloading every time you refresh the page. make sure the configuration allow_reload property is set to false.

You can read more about it here: http://symfony.com/doc/current/book/http_cache.html

查看更多
登录 后发表回答