vendredi 17 juin 2016

Passing dependency parameters to App::make() in Laravel

I think this should be easy, but I'm struggling to figure out exactly how it should work.

I have a class that uses a dependency. I need to be able to dynamically set parameters on the dependency from the controller:

$objDependency = new MyDependency();
$objDependency->setSomething($something);
$objDependency->setSomethingElse($somethingElse);

$objMyClass = new MyClass($objDependency);

How do I achieve this through the Service Container in Laravel? This is what I've tried but this seems wrong to me. In my AppServiceProvider:

$this->app->bind('MyClass', function($app,$parameters){

    $objDependency = new MyDependency();
    $objDependency->setSomething($parameters['something']);
    $objDependency->setSomethingElse($parameters['somethingElse']);

    return new MyClass($objDependency);
}

And then in the controller i'd use this like:

$objMyClass = App:make('MyClass', [
    'something'     => $something, 
    'somethingElse' => $somethingElse
]);

Is this correct? Is there a better way I can do this?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire