samedi 24 mars 2018

Laravel - caching external data in a model for a period of time

One field in model is loaded from an external resource. Loading from an external resources may take a lot of time so i would like to do it as rarely as possible. Here is what i have so far:

class User extends Model {
  private $loaded = false;
  private $name = null;

  getName(){
    if(!$this->loaded){
      $this->name = loadNameFromExternalResource($this->id);
      $this->loaded = true;
    }
    return $this->name;
  }
}

This works well within a single request. I can call Auth::user()->getName() as many times as i want and only the first time will result in loading from an external resource.

But that's not enough, i would also like to avoid this loading in the next requests. So Im thinking that it would be good to cache this field for a limited amount of time, for example an hour. Then each request would get the value from cache and only one request per hour would have to load it from external resource.

But I cant quite figure out how to do this within a model. Because there may be different instances of User model for different users within the same request i can just store it in cache with a static key. The best i could think of was to store it with user id, like this:

class User extends Model {
  private $loaded = false;
  private $name = null;

  getName(){
    if(!$this->loaded){
      if(Cache::has('user_name_' . $this->id)){
        $this->name = Cache::get('user_name_' . $this->id);
      } else {
        $this->name = loadNameFromExternalResource($this->id);
        Cache::put('user_name_' . $this->id, $this->name, 60);
      }
      $this->loaded = true;
    }
    return $this->name;
  }
}

But this solution seems kind of strange to me. What do you guys think? Can it be done better?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire