Answer the question
In order to leave comments, you need to log in
Laravel why variable when __construct() controller?
I often see code like this in Laravel:
public function __construct(Topic $topic)
{
parent::__construct();
$this->topic = $topic;
}
public function __construct(InvoiceRepository $invoiceRepo)
{
$this->invoiceRepo = $invoiceRepo;
}
public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo)
{
parent::__construct();
$this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo;
$this->taxRateRepo = $taxRateRepo;
}
public function __construct(AccountRepository $accountRepo, UserMailer $userMailer, ContactMailer $contactMailer)
{
parent::__construct();
$this->accountRepo = $accountRepo;
$this->userMailer = $userMailer;
$this->contactMailer = $contactMailer;
}
Answer the question
In order to leave comments, you need to log in
This is called DI (Dependency Injection). It is created when an instance of the class is created. Laravel, using reflection, finds dependencies in the class constructor and creates new instances, if the class declared in the constructor is already in the container and declared as shared or singleton, then Laravel does not create new instances, but "slips" them from the container.
Read at your leisure about DI and IoC
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question