Understanding DIC semantics from the First Application Walkthrough

I apologise if this is a more general PHP question than specific to Slim. I’ve been working through the first application walkthrough and came accross this:

In order to be able to render the view, we’ll first need to create a view and make it available to our application; we do that by adding it to the DIC. The code we need goes with the other DIC additions near the top of src/public/index.php and it looks like this:

$container['view'] = new \Slim\Views\PhpRenderer("../templates/");

My confusion is I thought that only closures should be used here? Or is there something else I’m missing?

Typically you would use a closure because often in the DIC you are doing a little more than just creating a new object. For example in the same tutorial notice the additional steps needed to create $container['logger'] and $container['db'], so in those instances a closure is used.

Ultimately accessing the container is just returning an object, so doing it through a closure or not doesn’t matter.

1 Like

OK, so looking back at this $app = new \Slim\App(["settings" => $config]); and adding some debugging output to the \Pimple\Container class (specifically in offsetSet) and seeing that settings and view both show up, as well as numerous closures, I see that everything (objects, variables) is done through the DIC. I think I presumed that passing in a settings array to new App(...) was doing something different, but I see that it’s just passing the array in to a new Container object anyway. Also, the DIC wasn’t mentioned during the passing of $config to the App constructor.

So, for my own learning, are all these values (objects, arrays, etc) referred to as dependency injection? Maybe I’m getting hung up on the idea that DI is about throwing objects in to other objects and ignoring other types of dependency? Again, sorry if this is less about Slim per se, but I’m just trying to wrap my head around it and whether this is a fairly standard way of doing this “correctly” in PHP.

There are certain services which are required by Slim to be in the container, one of them is ‘settings’ as you saw. The ones that are required, in addition to ‘settings’, are included from the Slim app itself by default. See the Required Services section of the DIC docs for the others. So yes, the Slim app itself is setting up some stuff in the DIC container for it to use itself.

I’m far from the right person to answer a question about the “correct” way of doing anything in PHP… I stay out of debates about IOC and service locators versus proper DI usage. I just like getting things done. I’ll defer to others about how “correct” this is.

2 Likes