Thursday, 28 July 2011

yii cache CacheDependency, memcache, file cache

Using cache in Yii mainly involves configuring and accessing a cache application component. The following application configuration specifies a cache component that uses memcache with two cache servers.

array(     ......     'components'=>array(         ......         'cache'=>array(              'class'=>'system.caching.CMemCache',             'servers'=>array(                 array('host'=>'server1', 'port'=>11211, 'weight'=>60),                 array('host'=>'server2', 'port'=>11211, 'weight'=>40),             ),         ),     ),  );
follow you create service cache<?php
class CacheService{

public $modelName;
public $action;
public $position;
public $page;
public $id;
public $sort;

public function __construct($modelName,$action,$position='',$id='',$page='',$sort=''){
$this->modelName = $modelName;
$this->action = $action;
$this->position = $position;
$this->id = $id;
$this->page = $page;
$this->sort = $sort;
}

public function createKey(){
$cacheName = "store.".$this->modelName.".cache.".$this->action;
if($this->position != ''){
$cacheName .='.'.$this->position;
}
if($this->id != ''){
$cacheName .='.'.$this->id;
}
if($this->page != ''){
$cacheName .='.'.$this->page;
}
if($this->sort != ''){
$cacheName .='.'.$this->sort;
}

return trim($cacheName);
}


public function createDependency(){
$dependencyName = "store_hdc.".$this->modelName.".cache.".$this->action;
if($this->position != ''){
$dependencyName .='.'.$this->position;
}
if($this->id != ''){
$dependencyName .='.'.$this->id;
}
if($this->page != ''){
$dependencyName .='.'.$this->page;
}
$dependencyName.='.status';

return trim($dependencyName);
}

//public function createDepen
}

follow get and set cache

public function getDetailProduct($pro_id) {
$row = array ();
$cache = false;
$cache_flag = false;
if (($cache = Yii::app ()->cache) !== null) {
$cacheService = new CacheService ("Products", "getDetailProduct",$pro_id,"");
$key = $cacheService->createKey ();
$cache = Yii::app ()->cache->get ( $key );
$dependency = $cacheService->createDependency ();
$cache_flag = true;
}
$cache = false;
if($cache == false){
$connect = Yii::app()->db;
$command = $connect->createCommand("SELECT * FROM products WHERE id ='$pro_id'");
$row = $command->queryRow();
if ($cache_flag) {
Yii::app ()->cache->set ( $key, $row, ConstantsUtil::TIME_CACHE_1800, new CGlobalStateCacheDependency ( $dependency ) );
}
}else{
$row = $cache;
}
return $row;
}


No comments:

Post a Comment