php laravel 中的构造方法对我来说不太清楚

construct method in php laravel is not so clear to me

我对为什么我们需要构造函数感到困惑,有人可以从我的控制器向我解释这段代码吗:

    public function __construct(MerchantService $merchantService,    PaymentService $paymentService){
    $this->merchantService = $merchantService;
    $this->paymentService = $paymentService;
}

我正在使用 laravel 开发管理面板。我们的老板希望结构是这样的:

controller -> service -> repository -> modal -> database

当我走这条路线时,它非常简单:

controller -> modal ->database.

但我必须按照第一个。上面的代码是来自控制器的示例

在上面的代码中有 2 个服务,MerchantServicePaymentService。但我不明白构造函数究竟用 Merchant service 变量和支付变量作为参数做了什么,它是否启动了 Merchant servicePaymentService 的对象??

这是一个设计模式,叫做depedency injection
这是一种很好的工作方式,因此您可以轻松编写测试或更改服务等。

您可以阅读有关 dependecy injection here on SO itself, or here on wikipedia 的更多信息。

The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

public function __construct(UserRepository $users)
{
    $this->users = $users;
}

In this example, the UserController needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context, our UserRepository most likely uses Eloquent to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the UserRepository when testing our application.

https://laravel.com/docs/5.3/container