I was just curious if there were a difference or preference on how to instantiate containers in Slim between the two options:
$app = new Slim\App;
$di = new Slim\Container
vs.
$app = new Slim\App;
$di = $app->getContainer();
They both work fine. In my apps I’ve been using the first instance to create a bootstrap of dependency containers and on my routes I use the second instance to instantiate controllers for the route as noted below:
$app = new Slim\App;
$di = new Slim\Container;
$di['service'] = function() {
return new App\Service;
};
// -------------------------------------
// some route
$c = $app->getContainer();
$c['Controller'] = function() use ($di) {
return new App\Controller($di->service);
};
$app->get('/route','Controller:dashboard');
$app->run();
@JustSteveKing Yep. I’ve gotten that part figured out. I’m just curious if there is a preference on how to instantiate the containers within the app or if it really doesn’t matter on how they’re set.
I prefer to setup the DI container and the Slim app in two separate steps.
<?php
// DI setup
$cnt = new Slim\Container;
$cnt['service'] = function() {
return new App\Service;
};
$cnt['controller'] = function() use ($cnt) {
return new App\Controller($cnt['service']);
};
// App setup
$app = new Slim\App($cnt);
$app->get('/route','Controller:dashboard');
$app->run();
Following this approach you can keep each step in a separate file, and have variations for different environments if you need them (e.g. di_prod.php, app_test.php)
@1ma I agree, although I use Controllers as an exception. Since I don’t share them I like to handle controllers on a ‘per route’ basis in their own container.