Created
April 18, 2013 14:56
-
-
Save g-pavlik/5413393 to your computer and use it in GitHub Desktop.
POC how to use traits for injecting functionality
to objects
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 | |
/** | |
* Created by JetBrains PhpStorm. | |
* User: gpawlik | |
* Date: 4/18/13 | |
* Time: 4:42 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
class ModuleInjectorTest extends PHPUnit_Framework_TestCase { | |
public function testTrue() | |
{ | |
$this->assertTrue(true); | |
} | |
public function testInjectingPlugin() | |
{ | |
$class = new SomeClass(); | |
$this->assertTrue($class->inject(new Module())); | |
} | |
public function testCanCallInjectedModule() | |
{ | |
$class = new SomeClass(); | |
$class->inject(new Module()); | |
$this->assertEquals( | |
999, | |
$class->doAndReturn(999) | |
); | |
} | |
} | |
class Module { | |
public function doAndReturn($par) | |
{ | |
return $par; | |
} | |
} | |
class SomeClass { | |
use ComponentInjector; | |
} | |
trait ComponentInjector { | |
private $modules = array(); | |
public function inject($component){ | |
$this->modules[] = $component; | |
return true; | |
} | |
public function __call($name, $arguments) | |
{ | |
foreach($this->modules as $module) { | |
if(method_exists($module, $name)) { | |
return call_user_func_array(array($module, $name), $arguments); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
points to consider:
finally - all three are possible by implementing different types of ComponentInjector traits