Cache
in package
implements
RouteAttributeInterface
Cache Attribute
Caches the response of a controller method at the server level for a specified duration. This is server-side caching to avoid expensive operations, not browser-level caching.
Usage:
#[Cache(for: 3600)] // Cache for 1 hour
#[Cache(for: 300, key: 'custom_key')] // Cache with custom key
Limitations:
- Only caches GET requests; POST, PUT, DELETE, and other methods are ignored
- Streaming responses or file downloads may not cache properly
- Cache key includes HTTP method, path, query string, and possibly user_id(), but not request headers
- Does not automatically invalidate related cache entries
- Cookies set in the response are cached and reused for all subsequent requests
- Large responses may impact cache storage performance
- Browser Cache-Control headers do not affect server-side caching behavior
Security Considerations:
- Ensure cache backend is properly secured and not accessible publicly
- Be aware that authorization checks happen before cache lookup
Attributes
- #[Attribute]
- \Attribute::TARGET_METHOD
Table of Contents
Interfaces
Properties
Methods
- __construct() : mixed
- after() : ResponseInterface|null
- Process the attribute after the controller is executed.
- before() : RequestInterface|ResponseInterface|null
- Process the attribute before the controller is executed.
- generateCacheKey() : string
Properties
$for
public
int
$for
= 3600
$key
public
string|null
$key
= null
Methods
__construct()
public
__construct([int $for = 3600 ][, string|null $key = null ]) : mixed
Parameters
- $for : int = 3600
- $key : string|null = null
after()
Process the attribute after the controller is executed.
public
after(RequestInterface $request, ResponseInterface $response) : ResponseInterface|null
Parameters
- $request : RequestInterface
- $response : ResponseInterface
Return values
ResponseInterface|null —Return ResponseInterface to replace the response Return null to use the existing response
before()
Process the attribute before the controller is executed.
public
before(RequestInterface $request) : RequestInterface|ResponseInterface|null
Parameters
- $request : RequestInterface
Return values
RequestInterface|ResponseInterface|null —Return RequestInterface to replace the request Return ResponseInterface to short-circuit and send response Return null to continue normal execution
generateCacheKey()
protected
generateCacheKey(RequestInterface $request) : string
Parameters
- $request : RequestInterface