I read this documentation about Service Container and also some other information on youtube but still not fully understand what is Service Container and how or when to use it so please if you can explain in simple words what is Service Container and how to use bind, make, resolving etc...
-
1stackoverflow.com/questions/37038830/…wujt– wujt2017-05-07 22:03:19 +00:00Commented May 7, 2017 at 22:03
-
stackoverflow.com/a/48239728/4701635Paresh Barad– Paresh Barad2018-01-13 12:10:03 +00:00Commented Jan 13, 2018 at 12:10
1 Answer
The service container is used for a concept "inversion of control, IoC"
It's basically a container where you resolve your services etc
class SomethingInMyApplication {
public function __constructor(LoggerInterface $logger) {
$logger->info("hello world");
}
}
$container->bind(ILoggerInterface::class, MySpecialLogger::class);
$something = $container->make(SomethingInMyApplication::class);
Your MySpecialLogger implements the interface, but you can also bind something else that implements the LoggerInterface::class
It can be made more complex with other design patterns like factories etc. So bind the right Logger implementation based on the configurartion.
All over your application you DI the LoggerInterface and therefor you can easily change the used implementation from MySpecialLogger to something else.
The container basically checks all the arguments in the __constructor and tries to resolve those types from the container.
$container->bind(ILoggerInterface::class, MySpecialLogger::class);
$container->make(SomethingInMyApplication::class);
// In the make method
$class = SomethingInMyApplication::class;
// Refelection to read all the arguments in the constructor we see the logger interface
$diInstance = $container->resolve(LoggerInterface::class);
$instance = new $class($diInstance);
// We created the SomethingInMyApplication