Last active
August 29, 2015 14:22
-
-
Save nimmneun/d50c22850c336d3ccc68 to your computer and use it in GitHub Desktop.
Rather dumb approach to an object factory *lol
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 | |
| /** | |
| * Universal Object factory ... well kinda :p | |
| * | |
| * @author nimmneun | |
| * @since 06.06.2015 03:07 | |
| */ | |
| class Trunk | |
| { | |
| /** | |
| * @var object[] | |
| */ | |
| private $objects = array(); | |
| /** | |
| * @var array with class dependencies. | |
| */ | |
| private $dependencies = array( | |
| 'App' => array( | |
| 'Keyword', | |
| 'Check', | |
| 'Config', | |
| 'UniCurl', | |
| ), | |
| 'Keyword' => array( | |
| 'Database', | |
| 'Validator', | |
| ), | |
| 'Database' => array( | |
| 'Config', | |
| 'PDO', | |
| ), | |
| ); | |
| /** | |
| * @param string $objectName is case sensitive! | |
| * @return object | |
| * @throws TrunkException | |
| */ | |
| public function get($objectName) | |
| { | |
| $dependencies = range(0,2); | |
| $i = 0; | |
| if (isset($this->objects[$objectName]) | |
| && $this->objects[$objectName] instanceof $objectName) | |
| { | |
| $desiredObject = $this->objects[$objectName]; | |
| } | |
| else | |
| { | |
| try | |
| { | |
| if (isset($this->dependencies[$objectName])) | |
| { | |
| foreach ($this->dependencies[$objectName] as $dependencyName) | |
| { | |
| $dependencies[$i++] = $this->get($dependencyName); | |
| } | |
| } | |
| $this->objects[$objectName] = $desiredObject = new $objectName($dependencies[0], $dependencies[1], $dependencies[2]); | |
| } | |
| catch (Exception $e) | |
| { | |
| throw new TrunkException('Unresolvable dependencies: '. $e->getMessage()); | |
| // todo: $this->getComplex($objectName); | |
| } | |
| } | |
| return $desiredObject; | |
| } | |
| } | |
| class TrunkException extends Exception {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment