When we need Container

I’m trying to write my first restAPI on Slim4.
A lot of things are not obvious for me.
For example when we need to use container. According to the documentation, the use of container is not required. Right?
When and for what should I use it?

I am sorry if my questions seems stupid.

Hello

Yes you’re right a container is not necessarily needed.
In a container you store all the dependencies.

Thanks.

Please give an example of logical reasoning:
application does so-and-so
… so the container is needed here
… or not needed

Short answer

You may not need a dependency injection container if you…

  • want to write and maintain SOLID code.
  • want to use dependency injection
  • don’t want to wire all dependencies manually
  • need a central place (“composition root”) for all dependencies
  • need a place for your database connection(s)
  • want to configure your dependencies in the same way

You may don’t need a container if you…

  • want to wire dependencies manually
  • load the configuration manually
  • only use closures as action handler
  • use global variables or custom hacks to handle database connections

Detailed answer:

A dependencies injection container (DIC) is a tool to define, store and inject the container depedencies. A DIC also acts as a factory for your dependencies. How depedencies are set in the container and how they are configured depend on the DIC implementation.

You (may) need a container when you write SOLID code and use (constructor) dependency injection.
The most common way to inject dependencies is via a class’s constructor. To do this you need to add an argument to the constructor signature to accept the dependency:

final class NewsletterMailer
{
    private $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    // ...
}

A dependency injection container helps to organize your dependencies.
In a larger codebase it’s getting harder to wire all dependencies manually.
For this reason some container implementations provide a feature called autowiring that detects and injects dependencies automatically for you.

Read more:

1 Like