@Cache
当前 Symfony 应用程序中已不再推荐使用此扩展包。此扩展包提供的所有注解现在都作为 PHP 属性内置在 Symfony 中。查看 Symfony 属性的完整列表。
@Cache
注解允许为过期和验证定义 HTTP 缓存头。
HTTP 过期策略
@Cache
注解允许定义 HTTP 缓存
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
/**
* @Cache(expires="tomorrow", public=true)
*/
class BlogController extends Controller
{
}
当类配置和方法配置之间存在冲突时,后者会覆盖前者
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()
{
}
}
注意
expires
属性接受 PHP strtotime()
函数理解的任何有效日期。
HTTP 验证策略
lastModified
和 Etag
属性管理 HTTP 验证缓存头。lastModified
将 Last-Modified
头添加到响应中,Etag
添加 Etag
头。
当响应未被修改时,两者都会自动触发逻辑以返回 304 响应(在这种情况下,控制器不会被调用)
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 9 10
public function my(Request $request, Post $post)
{
$response = new Response();
$response->setLastModified($post->getUpdatedAt());
if ($response->isNotModified($request)) {
return $response;
}
// your code
}
注意
Etag HTTP 头值是使用 sha256
算法哈希表达式的结果。
属性
以下是接受的属性及其 HTTP 头等效项的列表
注解 | 响应方法 |
---|---|
@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') |
注意
smaxage
、maxage
和 maxstale
属性也可以获取具有相对时间格式的字符串(1 day
、2 weeks
等)。
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。