Ergo\Registry::lookup PHP Method

lookup() public method

Looks up a key in the registry, with an optional closure that that will be executed and the result stored if the key doesn't exist (and there is no trigger).
public lookup ( $key, $closure = null ) : Object
return Object
    public function lookup($key, $closure = null)
    {
        // if a closure was provided and we missed, store it
        if (!is_null($closure) && !isset($this->_registry[$key]) && !isset($this->_triggers[$key])) {
            $this->_registry[$key] = $this->_memoize($closure($key));
        }
        // the registry stores closures
        if (isset($this->_registry[$key])) {
            $result = call_user_func($this->_registry[$key], $this);
            $this->_registry[$key] = $this->_memoize($result);
            return $result;
        } else {
            if (isset($this->_triggers[$key])) {
                call_user_func($this->_triggers[$key], $this);
                unset($this->_triggers[$key]);
                return $this->lookup($key);
            } else {
                throw new RegistryException("No entry for key '{$key}'");
            }
        }
    }

Usage Example

Example #1
0
 public function testTriggerTrumpsClosureOnMiss()
 {
     $registry = new Registry();
     $registry->trigger('my_key', function ($r) {
         $r->register('my_key', (object) array('source' => 'trigger'));
     });
     $result = $registry->lookup('my_key', function () {
         return (object) array('source' => 'closure');
     });
     $this->assertEquals($result->source, 'trigger');
 }