Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Bundles
  4. SensioFrameworkExtraBundle
  5. @Cache

@Cache

Edit this page
It's no longer recommended to use this bundle in current Symfony applications. All the annotations provided by this bundle are now built-in in Symfony as PHP attributes. Check out the full list of Symfony attributes.

The @Cache annotation allows to define HTTP caching headers for expiration and validation.

HTTP Expiration Strategies

The @Cache annotation allows to define HTTP caching:

1
2
3
4
5
6
7
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

/**
 * @Cache(expires="tomorrow", public=true)
 */
public function index()
{
}
1
2
3
4
5
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

#[Cache(expires: 'tomorrow', public: true)]
public function index()
{
}

You can also use the annotation on a class to define caching for all actions of a controller:

1
2
3
4
5
6
/**
 * @Cache(expires="tomorrow", public=true)
 */
class BlogController extends Controller
{
}
1
2
3
4
#[Cache(expires: 'tomorrow', public: true)]
class BlogController extends Controller
{
}

When there is a conflict between the class configuration and the method configuration, the latter overrides the former:

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * @Cache(expires="tomorrow")
 */
class BlogController extends Controller
{
    /**
     * @Cache(expires="+2 days")
     */
    public function index()
    {
    }
}
1
2
3
4
5
6
7
8
#[Cache(expires: 'tomorrow')]
class BlogController extends Controller
{
    #[Cache(expires: '+2 days')]
    public function index()
    {
    }
}

Note

The expires attribute takes any valid date understood by the PHP strtotime() function.

HTTP Validation Strategies

The lastModified and Etag attributes manage the HTTP validation cache headers. lastModified adds a Last-Modified header to Responses and Etag adds an Etag header.

Both automatically trigger the logic to return a 304 response when the response is not modified (in this case, the controller is not called):

1
2
3
4
5
6
7
8
9
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

/**
 * @Cache(lastModified="post.getUpdatedAt()", Etag="'Post' ~ post.getId() ~ post.getUpdatedAt().getTimestamp()")
 */
public function index(Post $post)
{
    // your code
    // won't be called in case of a 304
}
1
2
3
4
5
6
7
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

#[Cache(lastModified: 'post.getUpdatedAt()', etag: "'Post' ~ post.getId() ~ post.getUpdatedAt().getTimestamp()")]
public function index(Post $post)
{
    // your code
    // won't be called in case of a 304
}

It's roughly doing the same as the following code:

1
2
3
4
5
6
7
8
9
10
public function my(Request $request, Post $post)
{
    $response = new Response();
    $response->setLastModified($post->getUpdatedAt());
    if ($response->isNotModified($request)) {
        return $response;
    }

    // your code
}

Note

The Etag HTTP header value is the result of the expression hashed with the sha256 algorithm.

Attributes

Here is a list of accepted attributes and their HTTP header equivalent:

Annotation Response Method
@Cache(expires="tomorrow") $response->setExpires()
@Cache(smaxage="15") $response->setSharedMaxAge()
@Cache(maxage="15") $response->setMaxAge()
@Cache(maxstale="15") $response->headers->addCacheControlDirective('max-stale', 15)
@Cache(staleWhileRevalidate="15") $response->headers->addCacheControlDirective('stale-while-revalidate', 15)
@Cache(staleIfError="15") $response->headers->addCacheControlDirective('stale-if-error', 15)
@Cache(vary={"Cookie"}) $response->setVary()
@Cache(public=true) $response->setPublic()
@Cache(lastModified="post.getUpdatedAt()") $response->setLastModified()
@Cache(Etag="post.getId() ~ post.getUpdatedAt().getTimestamp()") $response->setEtag()
@Cache(mustRevalidate=true) $response->headers->addCacheControlDirective('must-revalidate')

Note

smaxage, maxage and maxstale attributes can also get a string with relative time format (1 day, 2 weeks, ...).

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Become certified from home

    Become certified from home

    Version:

    Table of Contents

    • HTTP Expiration Strategies
    • HTTP Validation Strategies
    • Attributes

    Symfony footer

    Avatar of Tristan Maindron, a Symfony contributor

    Thanks Tristan Maindron (@tmaindron) for being a Symfony contributor

    2 commits • 149 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony