<?php 

namespace NPS\Factory;

use Closure;

/**
 * Factory which temporarily stores created objects
 * @author Lukas Korinek
 */
trait TMemorizedFactory
{

    /**
     * @var array
     */
    private $memory = [];

    /**
     * Loads a factored object from the memory
     * @param mixed $entity Entity for which to load the object
     * @param Closure $callback
     * @return mixed
     */
    public function load($entity, Closure $callback)
    {
        $id = intval($entity->getId());
        if($id && array_key_exists($id, $this->memory))
        {
            return $this->memory[$id];
        }

        $object = $callback($entity);
        $this->memory[$id] = $object;

        return $object;
    }
    
}

