問題描述
在 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');
}
}
我有幾個(gè)問題:
使用 IlluminateHttpRequest
比使用 IlluminateSupportFacadesRequest
我不知道 $request->get() 是如何解析的,因?yàn)?IlluminateHttpRequest
中沒有函數(shù)名稱 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?
推薦答案
在控制器方法中請求注入功能總是更可取的,因?yàn)樵谀承┓椒ㄖ兴梢詭椭褂帽韱握埱?它們擴(kuò)展默認(rèn)請求類)驗(yàn)證,即將在進(jìn)入實(shí)際控制器方法之前自動(dòng)驗(yàn)證您的請求.這是一個(gè)很棒的功能,有助于創(chuàng)建纖薄和干凈的控制器代碼.
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.
使用默認(rèn)請求注入使您的控制器方法相似且更易于維護(hù).
Using default Request injection makes your controller's methods similar and easier to maintain.
還有對象注入總是比 Facades 好,因?yàn)檫@樣的方法 &對象更容易測試.
Also object injection is always better than Facades, because such methods & objects are easier to test.
get()
和input()
是不同類的方法.第一個(gè)是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.
這篇關(guān)于Laravel 請求 input() 或 get()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!