-
Notifications
You must be signed in to change notification settings - Fork 4
Container
A container resolves the dependencies of the specified class and inserts it to its container (list of instances) that can be used later.
In this example, let's create two classes like this:
class Foo
{
// ... Code
}
class Bar
{
protected $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
}
In order for Bar
to have an instance of Foo
, we need to do this:
$foo = new Foo;
$bar = new Bar($foo);
But what if you want to declare a class with a dependency that needs also a dependency to it? You need to that thing above again and again, which is cumbersome for a developer. In order to fix that problem, we need to use a container to resolve dependencies to classes with ease.
// ... Given that Foo and Bar classes were included
$container = new Container;
$bar = $container->add('Bar');
That's the basic functionality of a container. Some libraries also provides more functionalities other than that. You can find a list of libraries that implement the dependency injection design pattern at awesome-php.
To integrate a container to Slytherin, you will need to implement the component in a Container Interface. Take note that the said class is also implemented in Interop\ContainerInterface for interoperability but I added a new method in order for Slytherin can interact on the specified package. I have also provided a sample implementation of a container here.
Depending on the package that you want to use, you will need to instantiate first your dependencies before adding it as the container component in Components
.
$components = new Rougin\Slytherin\Components;
$container = new Rougin\Slytherin\IoC\Container;
// Instantiate your dependencies here...
$components->setContainer($container);