Skip to content

Instantly share code, notes, and snippets.

@pawlik
Created April 18, 2013 14:56
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 pawlik/5413393 to your computer and use it in GitHub Desktop.
Save pawlik/5413393 to your computer and use it in GitHub Desktop.
POC how to use traits for injecting functionality to objects
<?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);
}
}
}
}
@pawlik
Copy link
Author

pawlik commented Apr 18, 2013

points to consider:

  • should it call first method found among components or all?
  • if latter - how to make it run even if original object has called method?
  • maybe modules should register methods (inject(new Module(), 'doAndReturn;), and on trying to inject into class which already has that method thow exception?

finally - all three are possible by implementing different types of ComponentInjector traits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment