Search code examples
phpdependency-injectionslimpimple

Proper way to use Slim's dependency container


According to http://www.slimframework.com/docs/tutorial/first-app.html, the slim object is first created, and then the container is gotten and services are added to it.

$app = new \Slim\App(["settings" => $config]);
$container = $app->getContainer();
$container['logger'] = function($c) {
    ...
    return $logger;
};

However, http://www.slimframework.com/docs/concepts/di.html which is specifically about the dependency container is much stronger and states:

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.

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

Is one way more proper than the other?

How are services added when using the second approach?


Solution

  • Is one way more proper than the other?

    There are nealy the same, so in my opinion there is no proper way, but I've doing the second approach, because this way you can add logger and other stuff before you create the actual slim app instance.

    How are services added when using the second approach?

    The same as using you'r first approach

    $container = new \Slim\Container;
    $container['logger'] = function($c) {
        ...
        return $logger;
    };
    
    $app = new \Slim\App($container);