Laravel Model 优化 - 添加属性缓存(attribute cache)

问题背景

在咱们的项目中,使用到了大量的attribute函数,来改善咱们在面向业务时的调用方便和代码层面的优雅,可是一样也带来的必定的问题,会产生大量的重复计算和SQL调用,在应用上的性能上形成了一击。php

咱们来演示一下这个过程,首先定义出一个attribute,这样咱们能够方便经过的$user->posts_count,拿到用户发表的动态总数,像比原来的写法更加具备语义化,也更优雅了不少。缓存

public function getPostsCountAttribute()
{
        return $this->posts()->count();
}

可是遇到下面这种状况,就会糟糕了不少,会产生屡次的SQL查询,来形成服务端响应的缓慢app

if($user->posts_count > 30){
    //处理一
}

if($user->posts_count > 50){
    //处理二
}

if($user->posts_count > 100){
    //处理三
}

if($user->posts_count > 200){
    //处理四
}

像上面这样的写法的,咱们可能会形成4次SQL聚合运算,从而影响到咱们的响应速度,固然咱们也能够尝试改进代码规范来解决这个问题,可是仍然不能保证,这个属性被第二次、三次持续调用,那么方便、快捷的办法就是添加一层属性缓存,将获取后的值缓存到模型属性上。框架

属性缓存(attribute cache)

使用属性缓存的优点就是简单、快捷,无需借助第三方扩展,采用的是面向对象语言的原生优点,下面来实现一下:函数

在咱们Larvel框架的项目中,model都是继承于Eloquent\Model这个基类,咱们从新复写该基类操做比较繁琐,因此能够采用php为了实现多继承的trait来实现。post

首先实现一个AttributeCacheHelpertrait性能

<?php

namespace App\Traits;

trait AttributeCacheHelper
{
    private $cachedAttributes = [];

    public function getCachedAttribute(string $key, callable $callable)
    {
        if (!array_key_exists($key, $this->cachedAttributes)) {
            $this->setCachedAttribute($key, call_user_func($callable));
        }

        return $this->cachedAttributes[$key];
    }

    public function setCachedAttribute(string $key, $value)
    {
        return $this->cachedAttributes[$key] = $value;
    }

    public function refresh()
    {
        unset($this->cachedAttributes);

        return parent::refresh();
    }
}

主要是实现了三个函数,get和set用于获取和设置属性缓存,refresh重写了父类的刷新函数,每次刷新后都会清理掉对象缓存。this

而后咱们开始从新修改一下咱们的attribute,来添加对象缓存,首先是须要在Model上使用AttributeCacheHelper这个traitspa

public function getPostsCountAttribute()
{
    $method   = 'postsCount';
    $callable = [$this, $method];
    return $this->getCachedAttribute($method, $callable);
}

public function postsCount()
{
    return $this->posts()->count();
}

修改完成后,咱们再从新应用到场景中,就算执行一万次,也只会产生1次SQL查询,极大的提升了查询效率和响应速度。代码规范

for($i=0;$i<10000;$i++){
    // 仅产生一次真实查询,其他所有读取对象缓存数据
    dump($user->posts_count);
}

最后 happy coding 。

相关文章
相关标签/搜索