Yet another service container
Container DOES NOT use reflection and type hint information in any form.
Container keep two kind of values: services and parameters.
Service will instantiated when you call call it by name. Usually service is object type, but not nesessary. Mind it as "product" of some routine.
Methods: get()
and set()
.
Parameters are not instantiating, they just stored and retrieved.
Methods: getParameter()
and setParameter()
.
To install with composer:
composer require artoodetoo/container
There are special configuraton sections:
- root used to store basic values, which can be substituted into service definition.
shared
node defines shared services. after it created once it can be retrieved many times.multiple
node defines new instance created on every get() call
In other sections you can store any kind of information and retrieve it in dot notation (see below).
use R2\DependencyInjection\Container;
$config = [
'shared' => [
'view' => R2\Templating\Dirk::class
]
];
$c = new Container($config);
$c->get('view')->render('index');
$config = [
'ROOT' => '\var\www\mysite',
'PUBLIC' => '\var\www\mysite\public',
'shared' => [
'view' => [
'class' => R2\Templating\Dirk::class,
'options' => [
'views' => '%ROOT%/views',
'cache' => '%ROOT%/cache',
],
...
]
];
...
$c->get('view')->render('index');
$config = [
'shared' => [
'userManager' => App\UserManager::class,
'user' => '@userManager:getCurrentUser',
...
]
]
...
echo $c->get('user')->username;
There are two ways to inject container into service instance:
- Add interface
R2\DependencyInjection\ContainerAwareInterface
to service class and define setContainer() method. - Substitute container in constructor parameters. It is special name
CONTAINER
:
$config = [
'shared' => [
'example' => [
'class' => Example::class,
'container' => '%CONTAINER%',
],
]
];
$config = [
'options' => [
'cookie' => [
'name' => 'the-cookie',
'domain' => '.example.com'
]
];
...
setcookie(
$c->getParameter('options.cookie.name'),
$value,
0,
'/',
$c->getParameter('options.cookie.domain')
);
Any part of configuration can be read by getParameter, including special sections shared
and multiple
.
As for now, substitution patterns work in service production only.
Only parameters from config root can be used in substitution patterns.
The Container is open-source software, licensed under the MIT license