2012-03-08 73 views
1

我想在CakePHP的2.1採取的新的HTTP緩存功能優勢,加快我的網站: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(); 
} 

但是,這似乎並沒有解決問題

有誰知道如何讓這個工作,或者我做了什麼根本錯誤的?

回答

1

您可以嘗試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; 
    } 
    ... 
} 
+0

我試圖使用$ this-> response-> etag($ this-> Article-> generateHash($ article));但得到錯誤'數組到字符串轉換',並沒有追求它。我似乎無法找到任何有關generateHash的文檔,所以我不想調試它。 – Tomba 2012-03-08 17:23:56

+0

此外,我不相信我想使用Etags,除非絕對必要 – Tomba 2012-03-08 17:24:11

+1

您必須自己實現generateHash()方法以符合您的特定要求。你甚至不需要實現該方法,但你需要生成一個哈希 - 不知何故。在你的情況下,你需要像md5($ userId。' - '。$ articleId);如果你不喜歡使用etags,你需要生成一個哈希鍵,並找到另一種方法來緩存它。您也可以在頁面上使用緩存元素,在頁面中使用非緩存元素,以便視圖中用戶特定的部分。 – burzum 2012-03-08 21:29:05

0

我想我會發布的解決方案( s)我最終使用,以防萬一。

要完全爲登錄用戶禁用緩存:

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')); 
    } 
}