Laravel 请求 input() 或 get()
在 Laravel 5 中,请求对象的方法注入似乎比使用请求门面更受欢迎.
With Laravel 5 it seems like method injection for the Request object is preferred over using the Request facade.
<?php namespace AppHttpControllers;
use IlluminateHttpRequest;
class HomeController extends Controller
{
public function index(Request $request)
{
$email = $request->input('email');
// OR
$email = $request->get('email');
}
}
我有几个问题:
使用 IlluminateHttpRequest
比使用 IlluminateSupportFacadesRequest
我不知道 $request->get() 是如何解析的,因为 IlluminateHttpRequest
中没有函数名称 get()
.input() 和 get() 做同样的事情.
I have no idea how $request->get() is resolving as there is no function name get()
in IlluminateHttpRequest
. input() and get() does the same thing.
方法注入是否比使用 Facades 更好?
Is method injection better than using Facades?
推荐答案
在控制器方法中请求注入功能总是更可取的,因为在某些方法中它可以帮助您使用表单请求(它们扩展默认请求类)验证,即将在进入实际控制器方法之前自动验证您的请求.这是一个很棒的功能,有助于创建纤薄和干净的控制器代码.
In controller method Request injection functionality is always preferable, because in some methods it could help you to use Form Requests (they are extending default Request class) validation, that will validate your request automatically just before entering to the actual controller method. This is an awesome feature that helps to create slim and clean controller's code.
使用默认请求注入使您的控制器方法相似且更易于维护.
Using default Request injection makes your controller's methods similar and easier to maintain.
还有对象注入总是比 Facades 好,因为这样的方法 &对象更容易测试.
Also object injection is always better than Facades, because such methods & objects are easier to test.
get()
和input()
是不同类的方法.第一个是Symfony HttpFoundation Request的方法,input()
是继承Symfony Request类的Laravel Request类的方法.
get()
andinput()
are methods of different classes. First one is method of Symfony HttpFoundation Request, input()
is a method of the Laravel Request class that is extending Symfony Request class.
相关文章