FOSHttpCacheBundle

repository·3.x·Indexed 19 days ago

https://github.com/friendsofsymfony/foshttpcachebundle

A Symfony bundle providing advanced HTTP caching management. It enables sophisticated header configuration via path, host, or controller rules and supports active cache invalidation (purge, refresh, and tag-based) for proxies like Varnish, Nginx, and Symfony's built-in HttpCache. Key features include a Flash Message Listener to prevent session-based cache pollution and a CacheManager for manual or automatic invalidation.

Tokens
27.2K
Snippets
100
Records
124
Agent score
64%

What's inside FOSHttpCacheBundle

  1. Overview of FOSHttpCacheBundle functionality

    3.x

    The bundle provides several ways to manage cache behavior through attributes, configuration, or manual calls:

    FunctionalityAttributesConfigurationManually
    Set Cache-Control headersSymfony cache attributesSymfony cache control
    Tag and invalidate#[Tag]rulescache manager
    Invalidate routesinvalidatorscache manager
    Invalidate pathsinvalidatorscache manager
  2. Match requests by host, controller, query string, or path

    3.x

    When defining rules under cache_control, you can use the match key to target specific requests. Supported matching criteria include:

    • host: Match based on the request host using a regex (e.g., ^login.example.com$).
    • attributes: Match based on request attributes, such as the controller (e.g., attributes: { _controller: ^AcmeBundle:Default:.* }).
    • query_string: Match based on the presence of specific parameters in the URL (e.g., query_string: (^|&)token=).
    • path: Match based on the URL path using a regex (e.g., path: ^/$).
    fos_http_cache:
        cache_control:
            rules:
                # Match by host
                - match:
                        host: ^login.example.com$
                  headers:
                    cache_control: { public: false }
    
                # Match by controller
                - match:
                        attributes: { _controller: ^AcmeBundle:Default:.* }
                  headers:
                    cache_control: { public: true }
    
                # Match by query parameter
                - match:
                        query_string: (^|&)token=
                  headers:
                    cache_control: { public: false }
    
                # Match by path
                - match:
                        path: ^/
                  headers:
                    cache_control: { public: true }
  3. How User Context works with caching proxies

    3.x

    User Context allows you to cache content that varies based on user groups (e.g., guest, editor, admin) without storing a separate cache for every individual user. It uses a 'preflight' request mechanism to determine a unique hash for the user's context.

    The Workflow:

    1. A client requests a resource (e.g., /foo).
    2. The proxy server (like Varnish) intercepts the request and sends a hash request to a specific context hash route.
    3. The application receives this hash request. The UserContextListener intercepts it after the Symfony firewall is applied, calculates a hash via a HashGenerator, and returns a response containing the hash in a custom header (default: X-User-Context-Hash).
    4. The proxy server receives the hash, attaches it to the original client request for /foo as a header, and restarts the request.
    5. The application sees the header and, if configured, responds with Vary: X-User-Context-Hash. The proxy then caches the response specifically for that hash.

    This feature is compatible with Varnish and symfony-http-cache.

  4. How to use match sections to limit configuration

    3.x

    The match section is used within cache <headers>, invalidation <invalidation>, and tag rule <tags> configurations to restrict rules to specific requests and responses.

    A match section contains one or more criteria, all of which are treated as regular expressions. For a rule to apply, the request must satisfy all provided criteria.

    Important Note on Encoding: Some parts of the URL are URL-encoded. However, the expressions provided in this configuration MUST NOT be URL-encoded. The matcher automatically handles encoding before performing the match.

    match:
        host: ^login.example.com$
        path: ^/$
        query_string: (^|&)token=
  5. Use the Flash Message Listener to avoid session-based cache pollution

    3.x

    By default, Symfony flash messages are stored in the user session. When using features like user context to cache pages for logged-in users, including flash messages in the rendered HTML can cause notifications to be mixed up between different users or cached incorrectly.

    To solve this, the Flash Message Listener moves flash messages from the session into a cookie. The response is sent with a SET-COOKIE header, which ensures the response is not cached.

    Workflow:

    1. The server moves flash messages to a cookie.
    2. The client receives the cookie via a SET-COOKIE header.
    3. Client-side JavaScript reads the cookie, renders the messages into the DOM, and then deletes the cookie.

    Prerequisites: None.

  6. How cache_control rules work

    3.x

    The cache_control configuration uses a list of rules to manage HTTP response headers. Each rule consists of a match section and a headers section.

    1. Matching: When a request satisfies the parameters in the match section, the corresponding headers are applied to the response.
    2. Execution Order: Rules are evaluated in the order they are defined. The first match wins.
    3. Header Overwriting: By default, headers are only set if they are not already present on the response. However, you can control this behavior using:
      • A global defaults.overwrite setting.
      • A per-rule headers.overwrite: true option.

    If overwrite is true, the headers defined in that rule will replace existing headers.

    fos_http_cache:
        cache_control:
            defaults:
                overwrite: false
            rules:
                - match:
                    host: ^login.example.com$
                  headers:
                    overwrite: true
                    cache_control:
                        public: false
                        max_age: 0
                        s_maxage: 0
  7. Use the CacheManager to invalidate or refresh content

    3.x

    The FOS\HttpCacheBundle\CacheManager is used to explicitly invalidate or refresh content in your caching proxy.

    • Invalidating tells the proxy to stop serving a specific piece of content. The next time it is requested, the proxy fetches a fresh copy from the backend.
    • Refreshing forces the proxy to fetch a fresh copy of the content immediately.

    The CacheManager is available in the Symfony DI container via autowiring.

    use FOS\HttpCacheBundle\CacheManager;
    
    // Injected via autowiring
    public function __construct(CacheManager $cacheManager) { ... }
  8. Key features of FOSHttpCacheBundle

    3.x

    The bundle provides several capabilities for managing HTTP cache:

    • Path-based expiration: Configure cache expiration headers via application configuration based on the request path.
    • Invalidation schemes: Set up cache invalidation without writing custom PHP code.
    • Tag-based invalidation: Tag responses and invalidate specific cache entries using those tags.
    • High-performance invalidation: Send invalidation requests to proxies with minimal performance impact.
    • User-type differentiation: Differentiate cache versions based on user roles or types.
    • Custom HTTP cache clients: Provides tools to easily implement your own HTTP cache client.