Last active
December 14, 2015 06:49
-
-
Save mbrowne/5045620 to your computer and use it in GitHub Desktop.
(Hacky) DCI in PHP 5.4
This file contains 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 | |
/*********************************************************************** | |
UPDATE: See my improved example: https://gist.github.com/mbrowne/5047982 | |
************************************************************************/ | |
ini_set('display_errors', 1); | |
trait AssignableToRole | |
{ | |
protected $methods = array(); | |
public function addMethod($methodName, $methodCallable) | |
{ | |
if (!is_callable($methodCallable)) { | |
throw new InvalidArgumentException('Second param must be callable'); | |
} | |
$this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class()); | |
} | |
public function removeMethod($methodName) | |
{ | |
unset($this->methods[$methodName]); | |
} | |
//TODO: handle method name conflicts | |
public function addRole($traitOrClassName) { | |
if (trait_exists($traitOrClassName)) { | |
$className = $traitOrClassName.'Class'; | |
//We need a real class in order to be able to instantiate it, | |
//so we can pass the instance to getClosure() below | |
if (!class_exists($className)) { | |
eval('class '.$className.' {use '.$traitOrClassName.';}'); | |
} | |
} | |
elseif (!class_exists($traitOrClassName)) { | |
throw new InvalidArgumentException("Trait or class named '$roleTraitName' is not defined"); | |
} | |
else $className = $traitOrClassName; | |
$tmp = new $className; | |
$reflClass = new ReflectionClass($tmp); | |
$reflMethods = $reflClass->getMethods(); | |
foreach ($reflMethods as $method) { | |
$this->addMethod($method->name, $method->getClosure($tmp)); | |
} | |
} | |
//TODO | |
public function removeRole($traitOrClassName) { | |
} | |
public function __call($methodName, array $args) | |
{ | |
if (isset($this->methods[$methodName])) { | |
return call_user_func_array($this->methods[$methodName], $args); | |
} | |
throw RuntimeException('There is no method with the given name to call'); | |
} | |
} | |
class Person | |
{ | |
use AssignableToRole; | |
} | |
trait EmployeeRole | |
{ | |
function work() { | |
echo "I'm working on it..."; | |
} | |
} | |
$person = new Person; | |
$person->addRole('EmployeeRole'); | |
$person->work(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment