CakePHP 3.x:检查缓存是否有效

时间:2015-11-21 13:32:52

标签: cakephp caching cakephp-3.0

我的应用程序有Post模型。用户可以为created字段设置未来的日期时间,这样可以安排发布帖子。

现在,每次添加/编辑/删除帖子时,都会使用afterDelete()afterSave()方法:

  1. 我清空帖子缓存;
  2. 我在将来发布的帖子中取第一篇文章的created值,然后将此值保存在缓存中。
  3. 此值指示当前帖子缓存仍然有效的日期时间。

    现在,我需要这样:当执行find()帖子时,如果我正在使用缓存,请清空帖子缓存。

    我在哪里可以得到它?

    修改 我可能有未来日期的帖子,所以我只需要检索当前日期的帖子:

    $query = $this->Posts->find('all')
    ->where(['created <=' => new Time()]);
    

    但现在,通过此查询,我如何使用一点缓存?

    我可以这样做(PostsTable):

    public function afterDelete(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options) {
        $this->setNextToBePublished();
    }
    
    public function afterSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options) {
        $this->setNextToBePublished();
    }
    
    public function setNextToBePublished() {        
        $next = $this->find()
            ->select('created')
            ->where(['created >' => new Time()])
            ->order(['created' => 'ASC'])
            ->first();
    
        Cache::write('next_to_be_published', empty($next->created) ? FALSE : $next->created->toUnixString(), 'posts');
    }
    

    现在,每次添加/编辑/删除帖子时,都会缓存要发布的第一篇帖子的时间戳,以及将来的日期。

    现在我添加一个方法来检查缓存是否仍然有效并清空检查(PostsTable):

    public function checkIfCacheIsValid() {
        //Gets from cache the timestamp of the next record to be published
        $next = $this->getNextToBePublished();
    
        //If the cache is not valid, it empties the cache
        if($next && time() >= $next) {
            Cache::clear(FALSE, 'posts');
    
            //Sets the next record to be published
            $this->setNextToBePublished();
        }
    }
    

    现在终于可以做到了:

    $this->Posts->checkIfCacheIsValid();
    
    $query = $this->Posts->find('all')
    ->where(['created <=' => new Time()])
    ->cache('myposts', 'posts');
    

    请注意 使用cache()方法可以正常

    那么问题是什么? 我应该检查缓存是否有效,而不是在控制器中,而是在模型中。 但是,如果我使用cache()方法,则不会调用beforeFind()事件,它会自动恢复缓存。

    那我该怎么办?

0 个答案:

没有答案
相关问题