Created
October 26, 2014 16:48
-
-
Save bayleedev/919ba3b1120a37f75e1e 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 | |
| // Test | |
| $blaine = new Chain('Person', array( | |
| 'firstName' => 'Blaine', | |
| 'lastName' => 'Sch', | |
| 'city' => 'Tulsa', | |
| 'state' => 'Oklahoma', | |
| 'zip' => '74107', | |
| )); | |
| echo 'Address:' . PHP_EOL . $blaine->send('address'); | |
| // Setup | |
| class Chain { | |
| public $objs = array(); | |
| public function __construct($name, $data) { | |
| $obj = new $name($data); | |
| foreach ($obj->includes as $include) { | |
| $this->objs[] = new $include($this); | |
| } | |
| $this->objs[] = $obj; | |
| } | |
| public function send($method, $params = array(), $index = 0) { | |
| if (empty($this->objs[$index])) { | |
| return null; | |
| } | |
| $me = $this; | |
| $next = function() use($me, $method, $index) { | |
| return $me->send($method, func_get_args(), $index + 1); | |
| }; | |
| if (!method_exists($this->objs[$index], $method)) { | |
| return $next(); | |
| } | |
| array_unshift($params, $next); | |
| return call_user_func_array(array($this->objs[$index], $method), $params); | |
| } | |
| public function __call($method, $params) { | |
| return $this->send($method, $params, 0); | |
| } | |
| public function __get($var) { | |
| return $this->objs[count($this->objs)-1]->$var; | |
| } | |
| } | |
| // Real classes you create: | |
| class Person { | |
| public $includes = array( | |
| 'PersonName', | |
| 'PersonAddress', | |
| ); | |
| public $data = array(); | |
| public function __construct($data = array()) { | |
| $this->data = $data; | |
| } | |
| // Overwritten in PersonName | |
| public function name() { | |
| return $this->data['firstName']; | |
| } | |
| } | |
| class PersonAddress { | |
| public $parent = null; | |
| public function __construct($obj) { | |
| $this->parent = $obj; | |
| } | |
| // Calls name() method that is overwritten | |
| // This method is NOT defined on the parent | |
| public function address() { | |
| return $this->parent->name() . PHP_EOL . | |
| $this->parent->data['city'] . ', ' . $this->parent->data['state']; | |
| } | |
| } | |
| class PersonName { | |
| public $parent = null; | |
| public function __construct($obj) { | |
| $this->parent = $obj; | |
| } | |
| // Overwrite | |
| public function name($next) { | |
| return $next() . ' ' . $this->parent->data['lastName']; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment