It's some lovely Laravel magic, I think http://laravel.com/docs/5.1/container would be useful reading.
One of the reasons you would do dependency injection is to make swapping out implementations easier, especially during testing.
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".
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?
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?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community