我试图利用CakePHP 2.1中的新HTTP特性来加速我的站点:
class ArticlesController extends AppController {
public function view($id) {
$article = $this->Article->find(
'first',
array('conditions' => array('Article.id' => $id))
);
$this->response->modified($article['Article']['modified']);
$this->set(compact('article'));
}
}缓存工作正常,但不区分不同的用户(即,如果用户登录并访问已经缓存的页面,则显示先前缓存的页面,并且不显示特定于用户的内容)。我希望发生以下情况之一:
缓存。
我试着加入
if (AuthComponent::user('id')) {
$this->disableCache();
}但这似乎不能解决问题
有人知道如何让这件事起作用吗?还是我做了什么根本不对的事?
发布于 2012-03-08 15:35:33
您可以尝试etag缓存方法,并根据项目id和用户id生成一个哈希。
请参阅http://book.cakephp.org/2.0/en/controllers/request-response.html#the-etag-header
Etag标头(称为实体标记)是唯一标识请求资源的字符串。它非常像一个文件的校验和,缓存将比较校验和,以判断它们是否匹配。
要真正利用这个标题,您必须手动调用CakeResponse::checkNotModified()方法,或者将RequestHandlerComponent包含在控制器中:
<?php
public function index() {
$articles = $this->Article->find('all');
$this->response->etag($this->Article->generateHash($articles));
if ($this->response->checkNotModified($this->request)) {
return $this->response;
}
...
}发布于 2012-03-16 14:34:28
我想我会发布我最终使用的解决方案,以防它对任何人有帮助。
要完全禁用登录用户的缓存,请执行以下操作:
class ArticlesController extends AppController {
public function view($id) {
$article = $this->Article->find(
'first',
array('conditions' => array('Article.id' => $id))
);
if (!AuthComponent::user('id')) {
$this->response->etag($this->Article->generateHash($article));
}
$this->set(compact('article'));
}
}要为每个用户拥有一个单独的缓存(以及当没有人登录时):
class Article extends AppModel {
public function generateHash($article) {
if (AuthComponent::user('id')) {
return md5(AuthComponent::user('id') . '-' . $article['Article']['modified']);
} else {
return md5($article['Article']['modified']);
}
}
}
class ArticlesController extends AppController {
public function view($id) {
$article = $this->Article->find(
'first',
array('conditions' => array('Article.id' => $id))
);
$this->response->etag($this->Article->generateHash($article));
$this->set(compact('article'));
}
}https://stackoverflow.com/questions/9616234
复制相似问题