John Davidson

php - Laravel - Resolving a dependency with a constructor dependency from the container

0 comments
Message:


I want to resolve a class instance by a string which has dependency in its constructor from the container. I want to pass the constructor dependency in when I resolve the class.


A simple example I tested: Foo is the class I want to resolve and $id is a constructor argument:


class Foo
{
public function __construct(public $id)
{}
}

Binding in the service container:


$this->app->bind('foo', function($app, $id) {
return new Foo($id);
});

And resolving it from the container:


$foo = App::makeWith('foo', ['id' => 1]);

$foo is then resolved as


Foo 
{
+id: ["id" => 1],
}

Which shows that the public property $id is set as an array.


However, what if I don't want to have $id as an array, but an int?


I'd have to do the binding as follows:


App::bind('foo', function($app, $arg) {
return new Foo($arg['id']);
});

This feels extremely hacky. Is this an abuse of the service container?


Some may argue that it's not a good idea to pass in a constructor argument when resolving from the service container, rather make it stateless or use a setter. But if many methods in Foo will be using, say $id, it is most convenient and best practice to pass $id, as a constructor right?



My Answer:
app->bind('Foo', function($app, $parameters) { return new Foo($parameters['id']);});__Resolving the class instance from the container:_$id = 123;$foo = app('Foo', ['id' => $id]);echo $foo->id; // Output: 123

Rate this post

4 of 5 based on 4037 votes

Comments




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