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