Created
November 14, 2012 22:22
-
-
Save Ikke/4075281 to your computer and use it in GitHub Desktop.
DCI using php
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 | |
require('DCI/MethodDelegator.php'); | |
require('DCI/Role.php'); | |
class Foo extends Role{ | |
public function test() | |
{ | |
echo "I'm extended\n"; | |
echo "Even using data: {$this->value}\n"; | |
} | |
} | |
class TestData { | |
use MethodDelegator; | |
public $value; | |
} | |
$data = new TestData(); | |
$data->value = "Data value"; | |
$data->delegate('Foo'); | |
$data->test(); | |
?> | |
I'm extended | |
Even using data: Data value |
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 | |
Trait MethodDelegator | |
{ | |
private $roles = array(); | |
private $method_map = array(); | |
public function delegate($class) | |
{ | |
$role = new $class($this); | |
$this->roles[$class] = $role; | |
foreach(get_class_methods($class) as $method) | |
{ | |
$this->method_map[$method] = $role; | |
} | |
} | |
public function remove_delegation($class) | |
{ | |
$role = $this->roles[$class]; | |
unset($this->roles[$class]); | |
$this->method_map = array_filter( | |
$this->method_map, | |
function($stored_role) use($role){ | |
return $stored_role !== $role; | |
}); | |
} | |
public function __call($method, $args) | |
{ | |
if(! array_key_exists($method, $this->method_map)) { | |
throw new Exception("Method $method doesn't exist on this object"); | |
} | |
call_user_func_array( | |
array($this->method_map[$method], $method), $args | |
); | |
} | |
} |
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 | |
class Role | |
{ | |
private $data; | |
public function __construct($data) | |
{ | |
$this->data = $data; | |
} | |
public function __get($property) | |
{ | |
return $this->data->$property; | |
} | |
public function __set($property, $value) | |
{ | |
$this->data->$property = $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment