今天突然群里有人问memcache在YII中的使用,我简单的告诉他只要配置一下就行了,结果他弄了半天没弄好,看来我当初也是运气好一步到位的,随便自己做了一个小整理,给第一次使用YII memcache的朋友.
首先安装memcache,这个我就不多说了,目测我们公司美工百度一下都安装成功了,然后就得说一下了,在YII源码里面,YIIBase.php中$_coreClasses,这些是指默认加入的一些类,在654行'CMemCache' => '/caching/CMemCache.php',可以发现框架默认已经加载进来了,既然已经加载了我们就直接使用呗.
在项目的配置文件main.php中,找到组建components选项,同级会有一个urlManager,那么按照规则
'memcache'=>array(
'class'=>'CMemCache',
'servers'=>array(
array(
'host'=>'127.0.0.1',
'port'=>11211), ),), class对应的CMemCache是指上面提到过的默认加载类,memcache这个随意取就是了记得用的时候保持一直就好了.
既然有了memcache肯定是想着把session放进去啊,那么我们马上配置session组建,同memcache 'CHttpSession' => '/web/CHttpSession.php',也已经默认加载了,那么继续直接用呗,
'session' => array(
'class' => 'CHttpSession',
'timeout' => 7200,
'savePath' =>SESSION_DIR,
'servers' => array(
'memcache' => array('host'=>'127.0.0.1','port'=>11211), ), ),要添加多做session缓存,在servers里面加就是了,到这里很多时候公司需要自己对session做一些处理,这其实只是一个想法的问题了,自己写一个类继承CHttpSession, class Session extends CHttpSession,然后class要的只是一个类 'class' => 'Session',就搞定了,名字随意命名的,CMemCache一样也可以个性化改动,现在轮到使用了,已上面的情况我们首先打印var_dump(yii::app()->memcache);
object(CMemCache)[20] public 'useMemcached' => boolean false private '_cache' => object(Memcache)[22] public 'connection' => resource(33, memcache connection) private '_servers' => array 0 => object(CMemCacheServerConfiguration)[21] public 'host' => string '127.0.0.1' (length=9) public 'port' => int 11211 public 'persistent' => boolean true public 'weight' => int 1 public 'timeout' => int 15 public 'retryInterval' => int 15 public 'status' => boolean true private '_e' (CComponent) => null private '_m' (CComponent) => null public 'keyPrefix' => string '63b27c5b' (length=8) public 'behaviors' => array empty private '_initialized' (CApplicationComponent) => boolean true private '_e' (CComponent) => null private '_m' (CComponent) => null这代表你可以使用memcache了,那么我们进入YII 中/caching/CMemCache.php查看,这里面方法很少,很容易发现setValue($key,$value,$expire),getValues($keys)
那么yii::app()->memcache->setValue('abc', '123' );很快你就会发现CMemCache and its behaviors do not have a method or closure named "setValue".原因很简单,setValue方法是受保护的,所以我们只能去看看父类了咯,CMemCache extends CCache,在CCache很快就能找到public方法set get,所以
yii::app()->memcache->set( 'abc', '123' );
var_dump(yii::app()->memcache->get('abc'));我们就能直接使用了咯,这里注意2点,第一点我在前面文章说过那个memcache的小BUG问题,第二点
protected function getValue($key)
{
throw new CException(Yii::t('yii','{className} does not support get() functionality.',
array('{className}'=>get_class($this))));
}在CCache中写的供子类继承的方法,这种设计很不错,值得借鉴一下!