在 Laravel 中将依赖参数传递给 App::make() 或 App::makeWith()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37878033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:00:28  来源:igfitidea点击:

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

phplaravellaravel-5ioc-container

提问by jd182

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:

我如何通过 Laravel 中的服务容器实现这一点?这是我尝试过的,但这对我来说似乎是错误的。在我的 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

谢谢

回答by realplay

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

您可以在此处查看详细文档: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

或者使用 app() 助手

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

It is essentialto 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'.

这是必要的设置数组键作为参数变量名,否则会被忽略。因此,如果您的代码需要一个名为 $modelData 的变量,则数组键必须为 'modelData'。

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

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

注意:如果你用它来模拟,makeWith 不会返回 Mockery 实例。

回答by wired00

You can also do it this way:

你也可以这样做:

$this->app->make(SomeClass::class, ["foo" => 'bar']);