Skip to content

Instantly share code, notes, and snippets.

@rafi
Forked from Ikke/MethodDelegator.php
Created June 4, 2013 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafi/5705068 to your computer and use it in GitHub Desktop.
Save rafi/5705068 to your computer and use it in GitHub Desktop.
<?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
<?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
);
}
}
<?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