datatable.directory codebase
https://datatable.directory/
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
854 B
38 lines
854 B
7 years ago
|
<?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));
|
||
|
}
|
||
|
}
|