代码
class Test extends Controller {
function main()
{
// load the library
$this->load->library('simple_cache');
// key is the name you have given to the cached data
// will check if the item is cached
if (!$this->simple_cache->is_cached('key'))
{
// not cached, do our things that need caching
$data = array('print' => 'Hello World');
// store in cache
$this->simple_cache->cache_item('key', $data);
} else {
$data = $this->simple_cache->get_item('key');
}
$this->load->view('hello', $data);
}
}
simple cache library
<?php
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Simple_cache {
public $expire_after = 300;
public $cache_file = BASEPATH.'cache/';
function Simple_cache($life_time = '')
{
if (!empty($life_time))
{
$this->expire_after = $life_time;
}
}
function cache_item($key, $value)
{
if(!is_dir($this->cache_file))
{
$temp = explode('/',$this->cache_file);
$cur_dir = '';
for($i = 0; $i < count($temp); $i++)
{
$cur_dir .= $temp[$i].'/';
if (!is_dir($cur_dir))
{
@mkdir($cur_dir,0755);
}
}
}
if(!empty($value))
{
file_put_contents($this->cache_file.sha1($key).'.cache', serialize($value));
}
}
function is_cached($key)
{
if (file_exists($this->cache_file.sha1($key).'.cache')){
{
if((filectime($this->cache_file.sha1($key).'.cache')+$this->expire_after) >= time()))
{
return true;
}else{
delete_item($key);
return false;
}
} else {
return false;
}
}
function get_item($key)
{
$item = file_get_contents($this->cache_file.sha1($key).'.cache');
return unserialize($item);
}
function delete_item($key)
{
unlink($this->cache_file.sha1($key).'.cache');
}
function clear_all(){
}
}