Home  >  Article  >  Backend Development  >  Which one is better, dependency injection or ::call method, and what is the difference?

Which one is better, dependency injection or ::call method, and what is the difference?

WBOY
WBOYOriginal
2016-08-04 09:22:111661browse

Excuse me, laravel depends on injecting __construct(User $user) in the constructor of the class, and then all subsequent methods are directly called with $this->user. What is the difference between using User::find() directly? Which one do you recommend?

Reply content:

Excuse me, laravel depends on injecting __construct(User $user) in the constructor of the class, and then all subsequent methods are directly called with $this->user. What is the difference between using User::find() directly? Which one do you recommend?

This is the difference between static methods and dynamic methods in php classes.
Static methods can be used directly through class::function without class instantiation, but they must have the static keyword when declaring.
Dynamic methods must be called through instantiation of the class.

<code class="php">$class= new Class;
$class->somefunc();</code>

There is no better or worse between the two methods. The key depends on the scenario used.
Generally, if the logical correlation is not very close, it is recommended to use static methods. Because the dynamic method actually needs to pass in an implicit parameter: $this, which has a slight impact on performance.

I don’t understand PHP, but “relying on interfaces, not implementations” is a basic idea in the field of programming.
But the interface is not an actual object. How to call it requires injection. We can physically gather all injections into one place. In this way, when you want to modify the implementation of a class, you only need to modify one place.

<code>Class A{
    function __construct(User $user){
    }
}
Class B{
    function __construct(){
        $user = User::find(['id'=>1]);
    }
}
$user = User::find(['id'=>1]);
$a = new A($user);
$b = new B();
</code>

If there are business changes in the future, use
GoodUser extends User {}
The code needs to be changed

<code>Class B{
    function __construct(){
        $user = GoodUser::find(['id'=>1]);
    }
}
$user = GoodUser::find(['id'=>1]);
$a = new A($user);
$b = new B();
</code>

Have you noticed that class B has been changed? ! ! !
That is, it violates the principle of openness and closure.
That’s roughly it~ Heehee

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn