Created
November 8, 2012 19:03
-
-
Save piotrbelina/4040802 to your computer and use it in GitHub Desktop.
Dependency Injection using traits
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 | |
class Container | |
{ | |
protected $container = array(); | |
public function get($name) | |
{ | |
return $this->container[$name]; | |
} | |
public function set($name, $service) | |
{ | |
$this->container[$name] = $service; | |
} | |
} | |
interface ContainerAwareInterface | |
{ | |
function setContainer($container); | |
} | |
trait ContainerAware { | |
protected $container; | |
function setContainer($container) | |
{ | |
$this->container = $container; | |
} | |
} | |
class Test implements ContainerAwareInterface | |
{ | |
use ContainerAware; | |
public function __construct() | |
{ | |
print 'hello<br/>'; | |
} | |
public function testContainer() | |
{ | |
print $this->container->get('dummy'); | |
} | |
} | |
$container = new Container(); | |
$container->set('dummy', 'test from container'); | |
$test = new Test(); | |
if ($test instanceof ContainerAwareInterface) { | |
$test->setContainer($container); | |
} | |
$test->testContainer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment