如何在Laravel中缓存模型属性

问题描述 投票:3回答:2

在我当前的配置中,用户的电子邮件存储在远程服务器上,我需要通过curl任务进行访问。

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

这是我为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;
}
laravel
2个回答
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;
}

取决于您的用例进行调整(即会话,缓存,静态属性...)。


0
投票

如果您的班级扩展了Illuminate\Database\Eloquent\Model,则最好使用'属性',因为

1)没有创建额外的参数

2)其他功能将起作用,例如->refresh();

PS,不要用email_getting_code填充属性提取程序>

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

    public function getEmailAttribute(){
        $key = self::ATTRIBUTE_KEY_FOR_EMAIL;
        if (!array_key_exists($key, $this->attributes)) {
            $this->attributes[$key] = $this->getEmail();
        }
        return $this->attributes[$key];
    }

    private 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;
    }
}

在laravel 6.4上测试]

© www.soinside.com 2019 - 2024. All rights reserved.