CodeIgniter - 页面缓存

缓存页面将提高页面加载速度.如果页面被缓存,则它将以完全呈现状态存储.下次,当服务器收到缓存页面的请求时,它将直接发送到请求的浏览器.

缓存文件存储在 application/cache 中夹.可以基于每页启用缓存.在启用缓存时,我们需要设置时间,直到它需要保留在缓存文件夹中,在此期间后,它将自动删除.

启用缓存

可以通过在任何控制器的方法中执行以下行来启用缓存.

$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 文件夹中.要删除该文件,请访问以下网址.

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