繁体   English   中英

在laravel 5中创建自定义请求类的目的是什么?

[英]What is the purpose of creating a custom request class in laravel 5?

我下载了一个在Laravel 5.0中创建的简单应用程序。 我在Http \\ Requests下找到了一些文件,例如

HTTP \\请求\\ Request.php

    <?php namespace App\Http\Requests;

    use Illuminate\Foundation\Http\FormRequest;

    abstract class Request extends FormRequest {

        //

    }

HTTP \\请求\\管理\\ PhotoRequest.php

<?php namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class PhotoRequest extends FormRequest {

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'language_id' => 'required|integer',
            'photo_album_id' => 'required|integer',
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

}

这些课程的目的是什么?它是如何生效的?

您希望拥有瘦控制器以获得更好的可维护性。 当您拥有大量具有大量验证规则的表单字段时,您的控制器将变得臃肿。 因此,您需要移动模型中的所有数据逻辑,请求类中的验证逻辑等。

您可以在此处阅读有关单一责任原则的更多信

例如, rules()方法,当您提交表单时,它将检查字段是否经过验证。 在控制器中,您可以使用

function postForm(PhotoRequest $request){
    // Your Codes. You don't need to validate the data
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM