Reputation: 3330
I'm confused about why we need constructor and can someone explain me about this code from my controller :
public function __construct(MerchantService $merchantService, PaymentService $paymentService){
$this->merchantService = $merchantService;
$this->paymentService = $paymentService;
}
I am working on an admin panel with laravel . and our boss wants the stucture to be like this:
controller -> service -> repository -> modal -> database
it's pretty straight forward when i am going this route:
controller -> modal ->database.
but i have to follow the first one. The above code is a sample from the controller
in the above code there are 2 services, MerchantService
and PaymentService
. but i do not understand what exactly is the constructor doing with the Merchant service
variable and payment variable as params, is it initiating an object of Merchant service
and PaymentService
??
Upvotes: 1
Views: 773
Reputation: 163848
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
Upvotes: 1
Reputation: 2849
This is a design pattern, it's called depedency injection
.
This is a good way to work, so you can easyly write tests, or change the services, and more.
You can read more info about dependecy injection
here on SO itself, or here on wikipedia.
Upvotes: 0