問題描述
在 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.
這篇關于Laravel 請求 input() 或 get()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!