目录

CodeIgniter - 页面缓存( Page Caching)

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

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

启用缓存

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

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

其中$nminutes,minutes,您希望页面在刷新之间保持缓存状态。

禁用缓存

缓存文件在过期时会被删除,但是当您想要手动删除它时,则必须禁用它。 您可以通过执行以下行来禁用缓存。

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

例子 (Example)

创建一个名为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.phproutes.php文件,为上述控制器添加路由,并在文件末尾添加以下行。

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

在浏览器中键入以下URL以执行该示例。

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

访问上面的URL后,您将看到将在application/cache文件夹中创建此application/cache文件。 要删除该文件,请访问以下URL。

http://yoursite.com/index.php/cachecontroller/delete
↑回到顶部↑
WIKI教程 @2018