Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 723
jd182 Avatar asked Jun 17 '16 09:06

jd182


2 Answers

You can see detailed documentation here: https://laravel.com/docs/5.6/container#the-make-method

It's done like this:

$api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);

Or use the app() helper

$api = app()->makeWith(HelpSpot\API::class, ['id' => 1]);

It is essential to set the array key as the argument variable name, otherwise it will be ignored. So if your code is expecting a variable called $modelData, the array key needs to be 'modelData'.

$api = app()->makeWith(HelpSpot\API::class, ['modelData' => $modelData]);

Note: if you're using it for mocking, makeWith does not return Mockery instance.

like image 128
realplay Avatar answered Oct 02 '22 05:10

realplay


You can also do it this way:

$this->app->make(SomeClass::class, ["foo" => 'bar']);
like image 31
wired00 Avatar answered Oct 02 '22 04:10

wired00