cesarcarlos
cesarcarlos

Reputation: 1441

Getting the container in Slim 3

I'm learning the Slim 3 framework and when it comes to using the container I have come across two different ways. In some examples I've seen the following:

$container = new \Slim\Container;
$app = new \Slim\App($container);

while in others Slim is initialized first and then a function is used to get the container:

$app = new \Slim\App();
$container = $app->getContainer();

Is there a reason behind this? What is the difference in both methods or which is the preferred form? I couldn't even find documentation on getContainer() in the Slim User Guide.

Thanks.

Upvotes: 0

Views: 1834

Answers (1)

Fyntasia
Fyntasia

Reputation: 1143

As far as I can tell from the Slim 3 documentation page;

The $container is a Dependency Container, used for dependency injection.

Look at the next line on the documentation page: "You don’t have to provide a dependency container. If you do, however, you must inject the container instance into the Slim application’s constructor"

In other words, if you get the container from the App itself, it's preloaded with the required services. If you load a custom container into the app, you can add your own services to it before loading the app.

As to which is preferred, that all depends on what you do with the DI container. If you don't plan on injecting any services, you can just use the preloaded container from the App.

Upvotes: 1

Related Questions