jeudi 2 novembre 2017

Dependency Injecting a factory class

When I inject a dependency into my controller, it passes in a single instance of that class (singleton?).

I need to use this class as a factory - so will need to create many instances of the injected object.

For example, I have the simplified code..

Route::get('scores', function(Request $request, \App\Scorer $scorer){

    $score1 = $scorer->addSomeParams()->get();
}

So I am injecting my custom 'scorer' class and then setting the custom parameters in that object which determine what score to retrieve. This works great for one score, however, I want to return multiple scores like so...

Route::get('scores', function(Request $request, \App\Scorer $scorer){

    $score1 = $scorer->addSomeParams()->get();
    $score2 = $scorer->addSomeParams()->get();
}

Here, score2 conflicts with the parameters set on the one and only scorer object. I need to create a 'fresh' scorer object to get my second score.

I am not using any specific bindings. I am just using the 'reflection' method of injecting the dependencies.

What's the best way to do this in Laravel 5.4?

EDIT: I should also mention that the Scorer class has its own dependencies, so simply calling new \App\Scorer() would need me to instantiate all of that classes dependencies as well, so would be very messy.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lFo5QG
via IFTTT

Aucun commentaire:

Enregistrer un commentaire