John Davidson

php - Constructor Dependency Injection without passing when instantiating

0 comments
Message:


Using Laravel, I have a job with the following constructor:


public function __construct($accountId, DirectDebitInterface $directDebit)
{
$this->accountId = $accountId;
$this->directDebit = $directDebit;
}

When I dispatch this job:


CreateDirectDebitAccount::dispatch($accountId);

It will throw an error due to missing parameters of the constructor (the interface).


This of course makes sense, but is there a way for me to use the dependency injection without passing it into the constructor when dispatching?


I know I can drop the DI and just use:


$this->directDebit = App::make(XXX);

But I'm trying to understand the usage of DI etc.


Thanks.



My Answer:
accountId = $accountId;
$this->directDebit = $directDebit;
}

In Laravel, you can use constructor dependency injection to automatically resolve and inject dependencies when instantiating a class. This means that you do not need to manually pass the dependencies when creating an instance of the class.

To achieve this, you can bind the DirectDebitInterface implementation to the container in your service provider or configuration file. Laravel will then automatically resolve the dependency when creating an instance of the class.

For example, in your service provider or configuration file, you can bind the DirectDebitInterface implementation like this:

php
$this->app->bind(DirectDebitInterface::class, DirectDebitImplementation::class);


Then, when you instantiate the class that has the constructor with the DirectDebitInterface dependency, Laravel will automatically resolve and inject the DirectDebitImplementation instance for you:

php
$job = new YourJob($accountId);


Laravel will automatically inject the DirectDebitImplementation instance into the job's constructor without you needing to pass it explicitly.

Rate this post

4 of 5 based on 3299 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us