Sign in

PHP dependency injection and direct new

RAKANLO1 edited in Sat, 24 Sep 2022

I often see that other people's method function get (request $request) is equivalent to using the request object. Can't I directly use new request? Is there anything better about dependency injection

4 Replies
commented on Sat, 24 Sep 2022

Through container parsing, request can be easily modified. You can directly bind the corresponding entity object in the container without changing the existing business. Make the code more stable and testable.

How to understand service container and injection in laravel and ThinkPHP 5? -Some tricks in development

commented on Sat, 24 Sep 2022

It's the difference between bread made by others and bread made by yourself. Others know that you want bread, and they can give you all kinds of bread, as long as it is bread, but you can only make one kind of bread, so you can only make one kind of bread all the time, and you will be tired of it. So dependency injection can let you not care what kind of implementation is, just eat it, and the caller can give you different bread according to your needs.

commented on Sat, 24 Sep 2022

The injected request gives the right to create the request object to the caller, not the handler. In this way, when the caller needs to change (such as using the request subclass), the handler does not need to change.

commented on Sat, 24 Sep 2022

Reduce the coupling between programs

lock This question has been locked and the reply function has been disabled.