N
N
naneri2015-03-16 13:18:34
Laravel
naneri, 2015-03-16 13:18:34

Where to bind class implementation in Laravel?

I often see such Dependency Injection in projects.

public function __construct(AccountRepository $accountRepo, UserMailer $userMailer, ContactMailer $contactMailer)
    {
        parent::__construct();
        $this->accountRepo = $accountRepo;
        $this->userMailer = $userMailer;
        $this->contactMailer = $contactMailer;
    }

I understand that function variables must be implementations of classes - which are written before them. Where do the variables come from? Like you need to do app::bind()? Or how? I didn't understand something at all.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gladkovskiy, 2015-03-16
@SMGladkovskiy

Create an AccountRepository class. And in this class, write use, indicating the full path to the class file:

use app\Repositories\AccountRepository;
...
class SomeUsefullClassWithConstructorDI {
    public function __construct(AccountRepository $accountRepo, UserMailer $userMailer, ContactMailer $contactMailer)
    {
        parent::__construct();
        $this->accountRepo = $accountRepo;
        $this->userMailer = $userMailer;
        $this->contactMailer = $contactMailer;
    }

DI uses it...

V
Vyacheslav Plisko, 2015-03-16
@AmdY

That's right, it's app::bind, but it's better to hang an interface, and for app::bind to prescribe a specific implementation for this contract. Accordingly, to prepare such an object, you need to use app::make, it will resolve itself into the controller.
There is also a model binding
/edit/{user}
for such a binding you need to use Route::model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question