Reputation: 79
My question concerns a general topic for programming - dependency injection. But I will ask a question about the Laravel php framework.
How to correctly use the implementation of a class that expects a specific implementation of an object or variable value in the constructor? For example I have a class:
class User
{
public function __construct(
protected Phone $phone
) {
}
public function getPhoneNumber(): string
{
return $this->phone->number->string;
}
}
But $this->phone
should be a specific object, not just new Phone()
.
In the controller, for example, I can do this:
class UserController extends Controller
{
public function __construct(
protected User $user
) {
}
}
And then in any method of the UserController
I will get access to the $this->user
property which will contain the phone object, but it will not be a specific implementation of the object. And calling $this->user->getPhoneNumber()
will return an error.
Of course, I can use the setPhone()
method in the User class, but is it correct in relation to the User class? Because the phone property can be used in all methods of the User class, it is necessary for the User class to work.
In this case, how to use dependency injection correctly?
In addition, there may be situations when a class is called in a foreach and in each iteration specific values of some variable for the constructor are passed to it.
Upvotes: 0
Views: 2319
Reputation: 1583
The reason why you get an (empty) new Phone
object in your controller is because of how autowiring works in Laravel/PHP. If Phone
is not bound in the application container, it will just create a new instance.
If you want a specific instance of the Phone object (aka creating one before the application is ready), you should make use of Service providers in Laravel.
For example, if you want to make your Phone
instance and re-use it in your UserController
you can add this in your AppServiceProvider
:
public function register()
{
$this->app->singleton(Phone::class, function ($app) {
return new Phone(...);
});
}
More info on the subject: https://php-di.org/doc/autowiring.html https://laravel.com/docs/8.x/providers
Upvotes: 2