I am just now discovering dependency injection and I want to apply it to a medium sized project which I've been working on. I already have a classes folder which holds all the classes used in the system
/application/core/classes
I would like to know how I can configure PHP-DI to locate these classes according to how they are required.
Thanks in advance
Author of PHP-DI here, are you installing it with Composer?
If yes, then configure your folder in composer.json
and just require vendor/autoload.php
in your script. You can then start using the container, it should just work. For example:
$container = \DI\ContainerBuilder::buildDevContainer();
$yourObject = $container->get('YourClass');
Now be aware that this example is not dependency injection (as you can see there is no injection of anything here). When you get an object from the container ($container->get()
) you are coupling your code to the container.
It's fine to do this at the root of the application, e.g. to instantiate your controllers (or whatever other root objects you want to have). But the dependencies of the controllers should be injected, not fetched from the container (if you want to do dependency injection).
By the way there's a chat room if you want to discuss more topics: https://gitter.im/mnapoli/PHP-DI and of course the documentation.