CodeIgniter - 頁面快取



快取頁面可以提高頁面載入速度。如果頁面被快取,則它將以完全渲染的狀態儲存。下次伺服器收到對快取頁面的請求時,它將直接傳送到請求的瀏覽器。

快取檔案儲存在 **application/cache** 資料夾中。可以針對每個頁面啟用快取。啟用快取時,我們需要設定快取檔案在快取資料夾中保留的時間,超過該時間後,它將自動刪除。

啟用快取

可以透過在任何控制器的`method`中執行以下程式碼行來啟用快取:

$this->output->cache($n);

其中 **$n** 是您希望頁面在重新整理之間保持快取的 **分鐘數**。

停用快取

快取檔案過期時會被刪除,但如果要手動刪除它,則必須停用它。您可以透過執行以下程式碼行來停用快取:

// Deletes cache for the currently requested URI 
$this->output->delete_cache();
  
// Deletes cache for /foo/bar 
$this->output->delete_cache('/foo/bar');

示例

建立一個名為 **Cache_controller.php** 的控制器,並將其儲存在 **application/controller/Cache_controller.php** 中。

<?php 
   class Cache_controller extends CI_Controller { 
	
      public function index() { 
         $this->output->cache(1); 
         $this->load->view('test'); 
      }
		
      public function delete_file_cache() { 
         $this->output->delete_cache('cachecontroller'); 
      } 
   } 
?>

建立一個名為 **test.php** 的檢視檔案,並將其儲存在 **application/views/test.php** 中。

<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>CodeIgniter View Example</title> 
   </head>
	
   <body> 
      CodeIgniter View Example 
   </body>
	
</html>

修改 **application/config/routes.php** 中的 **routes.php** 檔案,為上述控制器新增路由,並在檔案末尾新增以下行:

$route['cachecontroller'] = 'Cache_controller'; 
$route['cachecontroller/delete'] = 'Cache_controller/delete_file_cache';

在瀏覽器中輸入以下 URL 來執行示例:

http://yoursite.com/index.php/cachecontroller

訪問上述 URL 後,您將看到為此建立的快取檔案位於 **application/cache** 資料夾中。要刪除該檔案,請訪問以下 URL:

http://yoursite.com/index.php/cachecontroller/delete
廣告
© . All rights reserved.