如何在Laravel中缓存模型属性

时间:2014-09-02 22:14:34

标签: laravel

在我目前的配置中,用户的电子邮件存储在远程服务器上,我需要使用卷曲任务进行点击。

幸运的是,当某个进程运行时,我每天只需要一次电子邮件。但是,当该进程运行时,需要多次引用该电子邮件。

这是我为email设置的当前访问者。问题是每次使用$user->email时都会调用curl请求。什么是避免这种情况的最佳方法?

UserModel中的

public function getEmailAttribute(){
    $curl = new Curl;
    $responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
        'client_id'=>getenv('dailycredId')
        ,'client_secret'=>getenv('dailycredSecret')
        ,'user_id'=>$this->id
    ));
    $response = json_decode($responseJson);
    return $response->email;
}

2 个答案:

答案 0 :(得分:2)

private $cached_email = false;

public function getEmailAttribute(){
  if ($this->cached_email){
    // if set return cached value
    return $this->cached_email;
  }
  // get the email
  $curl = new Curl;
  $responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
    'client_id'=>getenv('dailycredId')
    ,'client_secret'=>getenv('dailycredSecret')
    ,'user_id'=>$this->id
  ));
  $response = json_decode($responseJson);
  // cache the value
  $this->cached_email = $response->email;
  // and return
  return $this->cached_email;
}

根据您的使用案例进行调整(即会话,缓存,静态属性......)。

答案 1 :(得分:0)

扩展了雄辩的模型类

namespace App\Models\Utils;

use Illuminate\Database\Eloquent\Model as OldModel;

class MyModel extends OldModel
{
    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();
    }
}

建立您的课堂

class ElementWithEmail extends MyModel
{
    const ATTRIBUTE_KEY_FOR_EMAIL = 'Email';

    public function getEmailAttribute(){
        $key = self::ATTRIBUTE_KEY_FOR_EMAIL;                    
        $callable = [$this, 'getEmail'];

       return $this->getCachedAttribute($key, $callable);
    }

    protected function getEmail()
    {
        $curl = new Curl;
        $responseJson = $curl->post('https://www.dailycred.com/admin/api/user.json',array(
            'client_id'=>getenv('dailycredId')
            ,'client_secret'=>getenv('dailycredSecret')
            ,'user_id'=>$this->id
        ));
        $response = json_decode($responseJson);

        return $response->email;
    }
}

从您的代码中调用

$element = new ElementWithEmail();
echo $element->email;