qimnet / update-tracker-bundle
QIMNET 更新跟踪包
v1.5.2
2013-06-05 15:28 UTC
Requires
- php: >=5.3.2
- symfony/framework-bundle: >=2.2,<2.4-dev
Requires (Dev)
README
此包用于跟踪实体更新并根据更新时间在客户端或服务器端缓存结果。
配置
要使用此包,必须在项目中添加一个 UpdateTracker
实体。
可以使用以下代码:
<?php namespace ACME\MyBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Qimnet\UpdateTrackerBundle\Entity\UpdateTracker as BaseUpdateTracker; /** * @ORM\Entity */ class UpdateTracker extends BaseUpdateTracker { }
然后将实体的名称添加到您的 config.yml 文件中
qimnet_update_tracker: entity_name: 'ACME\MyBundle\Entity\UpdateTracker'
跟踪实体更改
要跟踪给定实体的更改,您有两种选择
- 在您的实体类上使用
Qimnet\UpdateTrackerBundle\Annotation\TrackUpdate
注解 - 在您的实体类中实现
Qimnet\UpdateTrackerBundle\UpdateTracker\TrackUpdateInterface
然后可以使用 qimnet.update_tracker.manager
服务跟踪更改。
使用 HTTP 缓存验证
要生成 HTTP 响应并使用 HTTP 缓存验证,请使用 qimnet.update_tracker.http_cached_response_factory
服务
<?php namespace ACME\MyBundle\Controller; class MyController { public function myAction() { $response = $this->get('qimnet.update_tracker.http_cached_response_factory') ->generate('my_namespace'); if ($response->isNotModified($this->getRequest())) { return $response; } // Fetch content $response->setContent('Some content'); return $response; } }
在 URL 中使用时间戳
时间戳 URL 对使用 HTTP 缓存过期头动态内容很有用。这可以用于
- 可以承受 URL 变化的内容
- ESI
要在您的 twig 模板中使用时间戳 URL,请使用 timestamped_path
、timestamped_url
和 timestamped_controller
函数。
以下是一个使用 ESI 的此类缓存策略的示例
namespace ACME\MyBundle\Controller; class MyController { /** * Every variation of the output of this method should update the * "my_update_tracker" UpdateTracker. * * @Cache(expires="+1year") **/ public function esiAction() { ... return $response; } }
{# /ACME/MyBundle/Resources/views/layout.html.twig #} ... {% render_esi(timestamped_url("acme_mybundle_mycontroller_esi", {}, "my_update_tracker")) %} ...
使用服务器端缓存
要使用服务器端缓存,请启用配置文件中的缓存管理器
qimnet_update_tracker: cache_manager: # True to enable the cache manager. enabled: true
然后可以使用 qimnet.update_tracker.cache_manager
服务请求缓存对象
<?php namespace ACME\MyBundle\Controller; use Symfony\Component\HttpFoundation\Response; class MyController { public function myAction($id) { $content = $this->get('qimnet.update_tracker.cache_manager') ->getObject('my_namespace', 'my_object/' . $id, function(){ //Fetch the content and return it return 'Some content'; }) return new Response($content); } }
您还可以通过使用带有 cache
策略的 render 标签直接从模板中渲染缓存的片段
{{ render(controller("MyBundle:MyController:myAction"), { strategy: "cache", "updateTrackerName": "my_update_tracker", ttl: 120 }) }}
当相应的更新跟踪命名空间更改时,自动删除缓存条目。