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