【发布时间】:2016-08-17 13:38:28
【问题描述】:
在Laravel Controller中,如果所有函数都使用Request,直接在构造函数中注入Request而不是在函数中是否正确?
下面的代码有效,我只是想知道它是否正确,是否有副作用......
class BananaController extends Controller
{
protected $request; // request as an attribute of the controllers
public function __construct(Request $request)
{
$this->middleware('auth');
$this->request = $request; // Request becomes available for all the controller functions that call $this->request
}
public function store()
{
$this->validate($this->request, [
'text' => 'required',
]);
// I save the banana attributes and the controller continues...
放轻松,关于stackoverflow的第一个问题:-)
[ADDENDUM] 明确地说,“常规”代码是:
class BananaController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, [
'text' => 'required',
]);
// I save the banana attributes and the controller continues...
【问题讨论】:
-
如果有master/children请求怎么办?哪一个将被注入构造函数?为此(为了区分),symfony 建议注入请求堆栈服务,而不是 Request 本身。
-
“主/子请求”是什么意思?我用谷歌搜索了它,但仍然不清楚......
-
在小应用程序中这是可以的。但是在未来的大型应用程序中,您需要将验证和授权与控制器分开。你会面临很多问题
-
@TortelliEngineer 您可以在代码中发出子请求。下面是例子:symfony.com/doc/current/templating/embedding_controllers.html 如果你愿意,我不知道哪个 Request 对象会被注入到构造函数中。
-
@KmasterYC 谢谢!我知道最好将验证放在其他地方,这只是请求的使用示例
标签: php laravel laravel-5 controller