instancecache trait

This commit is contained in:
2018-07-22 16:07:27 +02:00
parent a3ba68ea98
commit 3b123d7f08
5 changed files with 75 additions and 30 deletions
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Model;
/**
* Instance cache, used to avoid multiple retrieval of related models.
* Repeated calls to getCached() all return the same instance, without
* additional DB access.
*/
trait InstanceCache
{
private static $instanceCache = [];
public static function bootInstanceCache()
{
self::retrieved(function (Model $instance) {
self::$instanceCache[$instance->getKey()] = $instance;
});
}
/**
* Find entity by ID, either in DB, or in the internal cache.
*
* @param int $id
* @return Model|null
*/
public static function getCached($id)
{
return isset(self::$instanceCache[$id]) ?
self::$instanceCache[$id] :
(self::$instanceCache[$id] = self::find($id));
}
}
+6
View File
@@ -37,6 +37,12 @@ class Table extends Model
use Reportable;
protected $guarded = [];
/** Get owner from the instance cache (use when building table lists) */
public function cachedOwner()
{
return User::getCached($this->owner_id);
}
/** Owning user */
public function owner()
{
+2
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use AdamWathan\EloquentOAuth\OAuthIdentity;
use App\Models\Concerns\InstanceCache;
use App\Models\Concerns\Reportable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Notifications\Notifiable;
@@ -38,6 +39,7 @@ class User extends Authenticatable
{
use Reportable;
use Notifiable;
use InstanceCache;
/**
* The attributes that are mass assignable.