T
T
thorii2016-10-22 14:56:29
PHP
thorii, 2016-10-22 14:56:29

Can a DI container work like this?

$sys = new Container();
Next, the class reads the config, where it is written how to create an object, its constructor arguments, etc.
The first time you call a service like

$sys->get(Request::class);
//или по псевдониму как $sys->request

The container will create an object following the rules in the config.
You can dynamically register services through closures
$sys->notInitService = function(Container $c) {
return new NewService($c->get(ServiceArg::class));
}

Can it even work like that? There is a ton of information and articles on the net that are leveled in meaning and it is very difficult to find a clear explanation of DI

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Ne-Lexa, 2016-10-22
@thorii

Hello.
Of course it can.
Have a look at a good DI implementation - php-di.org/.
Your example would look like this:

$container->set(ServiceArg::class, function(){
    return new ServiceArgImpl();
});
$container->set('notInitService', \DI\object(NewService::class));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question