Created
April 20, 2012 10:21
-
-
Save kimausloos/2427632 to your computer and use it in GitHub Desktop.
Example for Pieter
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 | |
| /* | |
| Note, this DIC is quick and dirty, you should use and extend a real DIC | |
| like Pimple (https://github.com/fabpot/pimple) | |
| */ | |
| class DicContainer implements \ArrayAccess { | |
| /** | |
| * @var array contains all DIC items | |
| */ | |
| private $containerObjects = array(); | |
| public function offsetExists($name) { | |
| return isset($this->containerObjects[$name]); | |
| } | |
| public function offsetGet($name) { | |
| if (isset($this->containerObjects[$name])) { | |
| return $this->containerObjects[$name]; | |
| } | |
| return null; | |
| } | |
| public function offsetSet($name, $value) { | |
| $this->containerObjects[$name] = $value; | |
| } | |
| public function offsetUnset($name) { | |
| unset($this->containerObjects[$name]); | |
| } | |
| public function get($name) { | |
| if ( $this->offsetExists($name) && class_exists($this->offsetGet($name))) { | |
| $className = $this->offsetGet($name); | |
| return new $className; | |
| } | |
| } | |
| } | |
| class Core_User { | |
| public function getName() { | |
| return 'kamme'; | |
| } | |
| } | |
| class Custom_User extends Core_User { | |
| public function getName() { | |
| return "Hi, I'm " . parent::getName(); | |
| } | |
| } | |
| $container = new DicContainer(); | |
| $container['User'] = 'Custom_User'; | |
| /* | |
| Change the Custom_User to Core_User to see the core functionality. | |
| You should place this in your config, but can also automate this, see below | |
| */ | |
| echo $container->get('User')->getName(); | |
| /* stop here, the code below will break the code above otherwise :) */ | |
| __halt_compiler(); | |
| /* | |
| Like I said above, if you want, you can also make it fully automatic by adding something like this. | |
| I would recomment cacheing this if you use this way! | |
| */ | |
| $coreFiles = glob("Core/*.php"); | |
| foreach($coreFiles as $file) { | |
| $baseName = basename($file, '.php'); | |
| $container[$baseName] = 'Core_' . $baseName; | |
| } | |
| $customFiles = glob("Custom/*.php"); | |
| foreach($customFiles as $file) { | |
| //overwrite core files in $container and add files not in the core | |
| $baseName = basename($file, '.php'); | |
| $container[$baseName] = 'Core_' . $baseName; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment