Laravel 5 - 方法注入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27930189/
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
Laravel 5 - Method injection
提问by Dima Vergunov
How method injection works in Laravel 5(I mean implementation), can I inject parameters in custom method, not just in controller actions?
方法注入如何在 Laravel 5 中工作(我的意思是实现),我可以在自定义方法中注入参数,而不仅仅是在控制器操作中吗?
回答by Marty Aghajanyan
1) Read this articles to know more about method injection in laravel 5
1)阅读这篇文章以了解更多关于laravel 5中的方法注入
http://mattstauffer.co/blog/laravel-5.0-method-injection
http://mattstauffer.co/blog/laravel-5.0-method-injection
https://laracasts.com/series/whats-new-in-laravel-5/episodes/2
https://laracasts.com/series/whats-new-in-laravel-5/episodes/2
2) Here is simple implementation of method injection
2)这里是方法注入的简单实现
$parameters = [];
$reflector = new ReflectionFunction('myTestFunction');
foreach ($reflector->getParameters() as $key => $parameter) {
$class = $parameter->getClass();
if ($class) {
$parameters[$key] = App::make($class->name);
} else {
$parameters[$key] = null;
}
}
call_user_func_array('myTestFunction', $parameters);
you can also look at function
你也可以看看功能
public function call($callback, array $parameters = [], $defaultMethod = null)
in https://github.com/laravel/framework/blob/master/src/Illuminate/Container/Container.phpfile for more details
在 https://github.com/laravel/framework/blob/master/src/Illuminate/Container/Container.php文件中了解更多详细信息
3) You can use method injection for custom method
3)您可以将方法注入用于自定义方法
App::call('\App\Http\Controllers\Api\myTestFunction');
or for methods
或方法
App::call([$object, 'myTestMethod']);
回答by Muhammad Sadiq
Here is simple example of method injection,which we often used in laravel.eg
下面是方法注入的简单例子,我们在laravel.eg中经常用到
public function show(Request $request,$id){
$record = $request->find($id);
dd($record);
}
-Here we inject object of Request type,and we can inject model class object etc.
-这里我们注入请求类型的对象,我们可以注入模型类对象等。
Or General Example:
或一般示例:
class A{}
class B{
function abc(A $obj){}
}
-so function abc of class B will accept object of Class A.
like:
$obj = new A();
$obj2 = new B();
$obj2->abc($obj);