Reputation: 22703
Laravel 5 offers automatic dependency resolving if I type-hint the needed class/interface. But how should they be instantiated? Example:
public function __construct(Dependency $dependency) {
$this->dependency = $dependency;
}
And then, in another method, I'd like to create two instances, like this:
$one = new Dependency(1);
$two = new Dependency(2);
What is the most flexible and test-friendly way to do this?
Upvotes: 4
Views: 976
Reputation: 564
Excuse my poor joke, but it depends.
It looks like you have misunderstood the dependency resolving a little bit. In your example the property 'dependency' allready contains an instantiated object. If you need two different instances within another method you may instantiate them there, inject a container or use a factory. It depends on your needs.
a very short introduction to laravel dependency resolving
The automatic dependency resolving in laravel is provided by the service container and it is used to deliver an (allready) instantiated object. The resolved object must be binded to service container. The best way to do this is via service providers. Within the register method of a service provider you are able to do your bindings
$this->app->bind('Dependency', function ($app) {
return new Dependency();
});
In this example the container will return a new instance every time it is called.
If you need the same instance every time you may bind a singleton
$this->app->singleton('Dependency', function ($app) {
return new Dependency();
});
Upvotes: 1