基于模型的缓存

自定义模型内使用缓存

可以通过基础模型类 graceModel 的内置函数 cache()、clearCache()、removeCache() 来创建、删除缓存。

cache() 函数

功能 : 创建缓存( 自动判断缓存有效性 );  
参数 :
$name : 缓存名称
$id = null : 影响 id,字符串或数组形式 ( 作用 : 同一个缓存名称因为参数不同而产生不同的缓存数据 );
$queryMethod : 缓存数据不存在时执行的数据查询函数,建议以 __( 2个下划线 )开头;
$timer = 3600 : 缓存游戏时间,单位 : 秒;
$isSuper = true : 是否为一个全局缓存;// 非全局缓存会在名称前自动添加控制器及方法名;
返回 : 经过缓存机制处理的缓存数据

clearCache() 函数

功能 : 清空全部缓存;

removeCache() 函数

功能 : 清空全部缓存;
参数 : 
$name : 缓存名称
$id = null : 影响 id,字符串或数组形式 ( 作用 : 同一个缓存名称因为参数不同而产生不同的缓存数据 );
$isSuper = true : 是否为一个全局缓存;

模型类演示代码

Code phpLine:23复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
    • <?php
    • namespace phpGrace\models;
    • class students extends \graceModel{
    • public $tableName = 'students';
    • public $tableKey = 'st_id';
    • // 获取列表 缓存模式
    • public function getList(){
    • // 模型的 cache 函数会返回经过缓存逻辑处理后的最终数据结果
    • return $this->cache(
    • 'studentsList',
    • PG_PAGE, // 每一页数据一个缓存
    • '__getStudentsList'
    • );
    • }
    • // 获取列表 动态数据库查询模式
    • protected function __getStudentsList(){
    • echo '没有缓存数据,执行数据查询';
    • $db = db('students');
    • return $db->page(2)->order('st_id desc')->fetchAll();
    • }
    • }

    调用模型类代码

    Code phpLine:31复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
    • <?php
    • class indexController extends grace{
    • public $studentsModel;
    • public function __construct(){
    • parent::__construct();
    • // 初始化 students 模型
    • $this->studentsModel = new \phpGrace\models\students();
    • }
    • public function index(){
    • // 获取列表数据
    • $studentsList = $this->studentsModel->getList();
    • p($studentsList);
    • }
    • // 通过控制器利用模型清空缓存
    • public function clearAllCache()
    • {
    • // $this->clearCache(); 可以通过控制器直接清楚
    • $this->studentsModel->clearCache();
    • }
    • // 通过控制器删除某个具体缓存
    • public function delCache()
    • {
    • // 删除 studentsList 的第一页缓存数据
    • $this->studentsModel->removeCache('studentsList', 1);
    • }
    • }