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