-
Notifications
You must be signed in to change notification settings - Fork 4
Container
A container is a data structure whose instances are collections of other objects. Containers store objects in an organized way that follows specific access rules.
class Foo
{
public function baz()
{
// ...
}
}
class Bar
{
protected $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
public function booz()
{
return $this->foo->baz();
}
}
With the example code above, the Bar
class must have an instance of Foo
:
$bar = new Bar(new Foo);
To use the Bar
class, it needs to be implemented again like in the example code above which can be cumbersome. One of the solutions for this is to store it into a container once so it can be accessed anywhere in the application code:
use Rougin\Slytherin\Container\Container;
$container = new Container;
$bar = new Bar(new Foo);
$container->set('Bar', $bar);
// Returns an instance of Bar ---
$new = $container->get('Bar');
// ------------------------------
Some third-party packages for container provide additional functionalities like auto-wiring dependencies and more. With this, Slytherin supported the following third-party packages that can be integrated seamlessly to Slytherin core once their respective packages were installed:
-
AurynContainer
- uses the Auryn package by Daniel Lowrey (rdlowrey/auryn
) -
LeagueContainer
- uses the Container package from The PHP League (league/container
)
If not using the supported packages above, a list of packages that implements the dependency injection design pattern are also listed at the awesome-php repository. Once selected a specified package, it must be implemented in ContainerInterface
:
namespace Rougin\Slytherin\Container;
use Psr\Container\ContainerInterface as PsrContainerInterface;
interface ContainerInterface extends PsrContainerInterface
{
/**
* Sets a new instance to the container.
*
* @param string $id
* @param mixed $concrete
* @return self
*/
public function set($id, $concrete);
}