Created
December 17, 2013 19:08
-
-
Save joshuaadickerson/8010785 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function elkc() | |
| { | |
| static $elkc; | |
| if ($elkc === null) | |
| $elkc = new Elk_Container; | |
| return $elkc; | |
| } | |
| /** | |
| * @todo replace with Pimple | |
| */ | |
| class Elk_Container extends ArrayObject | |
| { | |
| protected $_lazy_load = array(); | |
| protected $_protected = array(); | |
| public function __construct() | |
| { | |
| parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS); | |
| } | |
| public function offsetGet($index) | |
| { | |
| if (isset($this->_lazy_load[$index])) | |
| { | |
| $this->offsetSet($index, $this->_lazy_load[$index]()); | |
| unset($this->_lazy_load[$index]); | |
| } | |
| return parent::offsetGet($index); | |
| } | |
| public function offsetExists($index) | |
| { | |
| return parent::offsetExists($index) || isset($this->_lazy_load[$index]); | |
| } | |
| public function offsetUnset($index) | |
| { | |
| if (!$this->isProtected($index)) | |
| { | |
| parent::offsetUnset($index); | |
| unset($this->_lazy_load[$index]); | |
| } | |
| } | |
| public function offsetSet($index, $newval) | |
| { | |
| if (!$this->isProtected($index)) | |
| parent::offsetSet($index, $newval); | |
| } | |
| /** | |
| * Add a class to be lazily loaded | |
| * @param string $key | |
| * @param string $class | |
| * @return Elk_Container | |
| */ | |
| public function lazyLoad($key, $class, $file = null) | |
| { | |
| $function = ''; | |
| if (!empty($file)) | |
| { | |
| $function .= 'require_once \'' . $file . '\';'; | |
| } | |
| $function .= 'return new ' . $class . ';'; | |
| $this->_lazy_load[$key] = create_function('', $function); | |
| return $this; | |
| } | |
| /** | |
| * Check if a property is protected (you can't change it) | |
| * @param string $property | |
| * @return bool | |
| */ | |
| public function isProtected($property) | |
| { | |
| return isset($this->_protected[$property]); | |
| } | |
| public function protect($property) | |
| { | |
| $this->_protected[$property] = true; | |
| return $this; | |
| } | |
| } | |
| $elkc = elkc(); | |
| $elkc['a'] = true; | |
| $elkc->lazyLoad('b', 'stdClass'); | |
| $elkc->lazyLoad('c', 'ArrayObject'); | |
| $elkc->c['hello'] = 'World'; | |
| $elkc->protect('c'); | |
| var_dump($elkc['a'], $elkc['b'], $elkc->c, $elkc); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment