账户中心 我的话题 我的评论 退出系统

使用自定义缓存类

自定义缓存类使用说明

phpGrace 1.2.1 版本新增了自定义缓存类的功能,您可以将某个相同类型的缓存封装为一个类文件,便于项目的复用 (:

实现步骤

在 phpGrace/caches/ 文件夹下创建您的自定义缓存类文件
文件命名规则 : 缓存类名称.php
类命名规则   : class 缓存类名称 extends \cacheBase{}
使用命名空间 : namespace phpGrace\caches;
例如 :
<?php
/*
 * 缓存类 针对 person 数据表
 * 作者 : 深海 5213606@qq.com
*/
namespace phpGrace\caches;
class persons extends \cacheBase{
	// 外部调用使用 cache 函数,自定义类只需实现数据获取算法
	public function __getPersonsList(){
		// 创建 数据表操作对象
		echo 'I am __getPersonsList, i have runed ......';
		$db = db('persons');
		return $db->order('id desc')->fetchAll();
	}
	
	public function __getAPerson(){
		echo 'I am __getAPerson, i have runed ......';
		$db = db('persons');
		return $db->where('id = ?', array($this->personid))->fetch();
	}
}

调用缓存

<?php
class testController extends grace{
	
	//__init 函数会在控制器被创建时自动运行用于初始化工作,如果您要使用它,请按照以下格式编写代码即可:
	/*
	public function __init(){
		parent::__init();
		//your code ......
	}
	*/
	public function index(){
		// 01. 实现 persons 数据表的查询缓存
		$personCache = new phpGrace\caches\persons();
		// 02. 利用 cache 函数自动完成缓存的构建读取工作
		// 使用 $this->personList ($this->) 即可将数据共享给视图
		$this->personList  = $personCache->cache('personsList', null, '__getPersonsList', 10, FALSE);
		//p($this->personList);
		
		// 缓存一条数据的例子
		// 假设 $this->gets[0] 为一个 person 数据主键的值,如 :
		// http://localhost/index/index/5
		if(empty($this->gets[0])){$this->gets[0] = 5;}
		// 利用对象属性给 __getAPerson 传递数据 ( 数据表的主键 )
		$personCache->personid = $this->gets[0];
		$this->person = $personCache->cache('persons', array($this->gets[0]), '__getAPerson', 10);
		p($this->person);
	}
}

关于缓存配置

自定义缓存与前面提到的控制器内直接实现的缓存共享同一份缓存配置, 配置实例 (phpGrace/config.php) :

01. 文件形式的缓存( 注意服务器文件夹写入权限 )

// 缓存类型
'allowCacheType'     => array('file', 'memcache', 'redis'),
// 缓存设置
'cache'             => array(
	'type'          => 'file',
	'pre'           => 'grace_'
)

02. memcache 形式的缓存

// 缓存类型
'allowCacheType'     => array('file', 'memcache', 'redis'),
// 缓存设置
'cache'             => array(
	'type'          => 'memcache',
	'host'          => '127.0.0.1',
	'port'          => '11211',
	'pre'           => 'grace_'
)
// memecache 形式的缓存会优先使用 memcached 扩展

03. redis 形式的缓存

// 缓存类型
'allowCacheType'     => array('file', 'memcache', 'redis'),
// 缓存设置
'cache'             => array(
	'type'          => 'redis', // 缓存类型
	'host'          => '127.0.0.1', // redis 主机地址
	'password'      => '123456',// 密码, 为空代表不需要密码
	'port'          => '6379', // 端口 
	'pre'           => 'grace_' // 缓存名称前缀
)