Support the ongoing development of Laravel.io →
IOC
Last updated 3 months ago.
0
  1. It's some lovely Laravel magic, I think http://laravel.com/docs/5.1/container would be useful reading.

  2. One of the reasons you would do dependency injection is to make swapping out implementations easier, especially during testing.

0

Regarding your comment

"And a second, more important one - what is the purpose? "

One advantage is the ability to test your software properly. If you have ever used phpUnit it enables you to mock objects. It is commonly referred to as "dependancy injection".

Last updated 7 years ago.
0

Thank you both!

As for testing - OK, I get it, but if this would be the only reason, It wouldn't be convincig enough for me:) It brings complexity to the code after all.

I understand the idea of dependancy injection, and I do understand that, as @tkprocat said, we can swap implementations - but, except for testing, is there a practical example of usefulness of this swapping?

0

Beside testing, you could use DI when dealing with datasource.

So in a case you are doing your app quickly in text-based datasource manner. It's fast and easy to implement.
Couple months later, you decided to change to a more practical datasource, let's say MongoDB. All you will need is to rewrite the implementation to MongoDB given by the "contract" (interface) you made to your text datasource, and just swap it in your app binding. It is injected to the controller anyway, so no modification is made to your controller.

The less modification you made to controller, the better. I doubt if you could really unit testing a controller, some say Yes, some say the other way. It seems to me testing controller is more likely on acceptance test side.

And acceptance tests could be complicated and time consuming.

konradpapala said:

Thank you both!

As for testing - OK, I get it, but if this would be the only reason, It wouldn't be convincig enough for me:) It brings complexity to the code after all.

I understand the idea of dependancy injection, and I do understand that, as @tkprocat said, we can swap implementations - but, except for testing, is there a practical example of usefulness of this swapping?

Last updated 7 years ago.
0

Sign in to participate in this thread!

LoadForge

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.