1

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...

shaedrich
  • 5,457
  • 3
  • 26
  • 42
zac
  • 4,495
  • 15
  • 62
  • 127

1 Answers1

1

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
Sander Visser
  • 4,144
  • 1
  • 31
  • 42