Creating Dependencies in Laravel 5, A Good Way

Laravel 5 offers automatic dependency detection if I type in - a hint of the required class / interface. But how to create them? Example:

public function __construct(Dependency $dependency) {
    $this->dependency = $dependency;
}

And then, in another method, I would like to create two instances, for example:

$one = new Dependency(1);
$two = new Dependency(2);

What is the most flexible and easy to test way?

+4
source share
1 answer

Sorry my poor joke, but it depends.

It sounds like you misunderstood how the addiction has changed a bit. In your example, the 'dependency' allready property contains an instance of the object. If you need two different instances in another method, you can create them there, enter a container, or use a factory. It depends on your needs.

laravel

laravel (allready) -. . - .

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

, .

, singleton

$this->app->singleton('Dependency', function ($app) {
    return new Dependency();
}); 
+1

All Articles