Simple PHP container with lazy load and autowiring
composer require wamania/containerEach class of your project can be a service.
<?phpuseWamania\Container;
class OneService
{
}
$container = newContainer();
$oneService = $container->get(OneService::class);Throw an NotFoundException if the service has not been built yet and if the class doesn't exists.
<?phpuseWamania\Container;
$container = newContainer();
$oneService = $container->has(OneService::class);Return true if the service has been built or if the class exists, otherwise return false
if you have dependances between your services, the container will try to build them if it can.
class OneService
{
}class AnotherService
{
private$oneService;
publicfunction__construct(OneService$oneService)
{
$this->oneService = $oneService;
}
publicfunctiongetOneService()
{
return$this->oneService;
}
}<?phpuseWamania\Container;
$container = newContainer();
$anotherService = $container->get(AnotherService::class);
$oneService = $anotherService->getOneService();Be careful to circular reference :
- if OneService need AnotherService
- AND if AnotherService need OneService
the container will throw a ContainerException.
If you try to inject an argument which is neither a class/service nor a parameter, and which cannot be null by default, it will throw a ContainerException.
You can pass parameters to your container and inject them in your services.
<?phpclass Db
{
private$host;
private$user;
private$password;
// we have defined Container::PARAMETER_PATTERN = '_parameter_%s'// if the container find the pattern in an argument, it inject the corresponding parameter valuepublicfunction__construct($_parameter_host, $_parameter_user, $_parameter_password)
{
$this->host = $_parameter_host;
$this->user = $_parameter_user;
$this->password = $_parameter_password;
}
}<?phpuseWamania\Container;
$parameters = [
'host' => 'localhost',
'user' => 'user',
'password' => 'secret'
];
$container = newContainer($parameters);
$db = $container->get(Db::class);