php - Laravel 请求 : it's correct injecting Request directly in the controller constructor?

标签 php laravel laravel-5 controller

在 Laravel Controller 中,如果所有函数都使用 Request,那么直接在构造函数而不是函数中注入(inject) 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 的第一个问题 :-)

[附录] 明确地说,“常规”代码是:

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...

最佳答案

我一直在使用相同的技术通过请求保护我的所有资源 Controller 路由(例如检查登录用户是否有权访问该资源)

但是,从 Laravel 5.3 开始, Controller 构造函数现在在中间件执行之前运行,它实际上破坏了请求中的路由模型绑定(bind)。

因此,如果您将请求直接注入(inject)到 Controller 方法中,就像在 Laravel 文档中一样,并且如果您有任何绑定(bind)到路由的模型,它会很好地解决它,但是如果您在 Controller 构造函数中注入(inject)请求并尝试访问您的请求中的模型如下所示 - 它将仅返回资源 ID 而不是模型。

//Route service provider
Route::model('resource', MyModel::class);
//Request class
public function authorize()
{
    //We expect to get a resource or null
    //But now it just returns the resource id
    if (!is_null($this->resource))
    {
        return $this->resource->createdBy->id == $this->getLoggedUser()->id;
    }
}

关于php - Laravel 请求 : it's correct injecting Request directly in the controller constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38998282/

相关文章:

php - Zend,如何从 Action Helper 中访问当前路线

javascript - Jquery Ui 可排序 : how to detect each fired event?

php - Laravel 4 - 试图获取非对象的属性

forms - Laravel 5.0 路由模型绑定(bind)在销毁操作中不起作用

php - AngularJS 使用 FormData API 上传多个文件

php - Laravel POST 调用返回 index() 函数而不是 store()

php - 检查 store_id Magento

php - 为什么事件记录模式不适用于丰富的领域模型?

php - Laravel $request->has ('name' )不起作用

laravel - 如何停止工匠队列 :listen command eating all CPU?