N
N
naneri2015-12-30 12:59:02
Laravel
naneri, 2015-12-30 12:59:02

Laravel why variable when __construct() controller?

I often see code like this in Laravel:

public function __construct(Topic $topic)
    {
    	parent::__construct();
        $this->topic = $topic;
    }

I wanted to ask - where does the $topic variable come from and where is it declared? I just can't understand at all where the controller class is declared and where the variable comes from.
Here are some more examples of controllers:
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

1 answer(s)
I
Ivan Brezhnev, 2015-12-30
@naneri

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 question

Ask a Question

731 491 924 answers to any question