|
本帖最后由 lxylxy888666 于 2012-12-5 22:04 编辑
memcache相信都知道熟悉了
写个类似DB的驱动,加入核心里
比较简单,写个文章凑个数
db的用法
$this->load->database();
然后就可以直接db对象进行数据库操作了
mem也要做到类似这样
$this->load->memcache();
然后就可以用mc对象进行缓存操作了
创建libraries下类:
Memcache
PHP复制代码
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Memcache Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Memcaches
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/Memcaches.html
*/
class CI_Memcache {
var $host;
var $port;
var $timeout;
var $mc;
public function __construct ( $memcache_config = array())
{
log_message ('debug', "Memcache Class Initialized");
$this->CI =& get_instance ();
$r = $this->CI->config->load('memcache');
if( !$memcache_config ) {
$memcache_config = $this->CI->config->item('memcache');
}
if( $memcache_config ) {
$this->host = isset( $memcache_config['host'] ) ? $memcache_config['host'] : 'localhost';
$this->port = isset( $memcache_config['port'] ) ? $memcache_config['port'] : '11211';
$this->timeout = isset( $memcache_config['timeout'] ) ? $memcache_config['timeout'] : '60';
return true;
}
return false;
log_message ('debug', "Memcache successfully run");
}
/**
* init memcache
* @return Memcache
*/
public function init ()
{
$key = $this->host . '-' . $this->port;
if( !$this->mc[$key] ) {
$memObj = new Memcache ();
$memObj ->connect($this->host, $this->port, $this->timeout);
return $this->mc[$key] = $memObj;
} else {
return $this->mc[$key];
}
}
}
复制代码
然后在Loader.php
里加memcache方法:
PHP复制代码 /**
* memcache Loader
*
* @param string the DB credentials
* @param bool whether to return the DB object
* @param bool whether to enable active record (this allows us to override the config setting)
* @return object
*/
public function memcache($params = '', $return = FALSE)
{
$CI =& get_instance();
$CI->load->library('memcache');
$this->memcache = new CI_Memcache();
$CI->mc = $this->memcache->init();
} 复制代码
当然,要增加配置文件
application/config/memcache.php
PHP复制代码
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['memcache']['host'] = 'localhost';
$config['memcache']['port'] = '11211'; 复制代码
最后,你就可以在controller或model里调用了
PHP复制代码 /**
* memcache调用
*/
public function memcache ()
{
$this->load->memcache();
$key = 'admin_memcache';
$this->mc->set($key, time());
echo $this->mc->get( $key );
} 复制代码
简单吧,ci易用好改,5年如一日,支持~~~
|
|