Skip to content

Instantly share code, notes, and snippets.

@mbrowne
Last active December 14, 2015 06:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrowne/5045620 to your computer and use it in GitHub Desktop.
Save mbrowne/5045620 to your computer and use it in GitHub Desktop.
(Hacky) DCI in PHP 5.4
<?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