Skip to content

Instantly share code, notes, and snippets.

@piotrbelina
Created November 8, 2012 19:03
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 piotrbelina/4040802 to your computer and use it in GitHub Desktop.
Save piotrbelina/4040802 to your computer and use it in GitHub Desktop.
Dependency Injection using traits
<?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