CodeIgnitor 缓存驱动类的使用

分类: 编程 标签: codeignitor

最近在给 redis 驱动类添加新的方法时又陷入了疑惑中,理不清这里面的类关系,所以这次彻底梳理一下。

CodeIgnitor 中使用缓存是通过 Libaray 下的 CI_Cache 代理调用 drivers 下的缓存驱动实现类(Cache_redis)方式进行的。

$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

if ( ! $foo = $this->cache->get('foo'))
{
        echo 'Saving to the cache!<br />';
        $foo = 'foobarbaz!';

        // Save into the cache for 5 minutes
        $this->cache->save('foo', $foo, 300);
}

echo $foo;
class CI_Cache extends CI_Driver_Library {
    protected $valid_drivers;
    protected $_cache_path;
    protected $_adapter;
    protected $_backup_driver;
    public $key_prefix;

    public function __construct();
    public function get();
    public function save();
    public function delete();
    public function increment();
    public function decrement();
    public function clean();
    public function cache_info();
    public function get_metadata();
    public function is_supported();
}
$this->load->driver('cache');
$this->cache->apc->save('foo', 'bar', 10);

// 文件缓存
$this->load->driver('cache');
$this->cache->file->save('foo', 'bar', 10);

// memcache 缓存
$this->load->driver('cache');
$this->cache->memcached->save('foo', 'bar', 10);

// redis 缓存
$this->load->driver('cache');
$this->cache->redis->save('foo', 'bar', 10);
|- app
|- system
 |- libraries
  |- Driver.php
  |- Cache
   |- Cache.php
   |- drivers
    |- Cache_apc.php
    |- Cache_file.php
    |- Cache_memcache.php
    |- Cache_redis.php
    |- Cache_wincache.php
// ... some code
// Instantiate, decorate and add child
$obj = new $class_name();
$obj->decorate($this);
$this->$child = $obj;
return $this->$child;

至此,CI_Cache 的所有内置类的关系已经全部说明完毕。

项目扩展

|- app
 |- libraries
  |- Cache
   |- Che300_Cache.php
   |- drivers
    |- Cache_predis.php
    |- Che300_Cache_redis.php
class Che300_Cache extends CI_Cache
{
	public function __construct()
	{
		parent::__construct();
		$this->valid_drivers[] = 'predis';
	}
}
$this->load->driver('cache');
$this->cache->predis->set('key', 'value');
$this->load->driver('cache');
$this->cache->redis->set('key', 'value');