1

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

Stanley Ngumo
  • 4,089
  • 8
  • 44
  • 64
  • Don't you say `DI` but want `_autoload`? Also, please do not use `DI` when you don't really need it. http://www.tonymarston.net/php-mysql/dependency-injection-is-evil.html – Forien Feb 02 '15 at 14:34
  • @Forien - I am already aware of autoloading and I use it but it would really help since my classes dont allow for a lot of flexibility which would be adequately by DI – Stanley Ngumo Feb 02 '15 at 14:40
  • Really @Forien, you quote Marston? ¯\_(ツ)_/¯ – Jay Blanchard Feb 02 '15 at 14:53
  • @Forien are you serious? The guy wants to learn about DI and you just dump "Please don't use it when you don't need it"… Might have said "Please stop your learning because I don't like it". – Matthieu Napoli Feb 02 '15 at 20:33

1 Answers1

2

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.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • Thanks a lot for your response but I'm not using Composer, is it possible for me to integrate it directly into my project? – Stanley Ngumo Feb 03 '15 at 13:48
  • Yes it's possible. You need to download PHP-DI and download its dependencies (and dependencies of those dependencies) and register those classes in your autoloader. Now you might see why using Composer is much simpler maybe give it a try ;) Also, add your own classes to your autoloader. – Matthieu Napoli Feb 03 '15 at 21:37
  • Have started experimenting with Composer and will definitely start using it :-) Thanks – Stanley Ngumo Feb 04 '15 at 10:36