简体   繁体   English

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

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

I downloaded a simple app which is created in Laravel 5.0. 我下载了一个在Laravel 5.0中创建的简单应用程序。 I found some files under Http\\Requests eg 我在Http \\ Requests下找到了一些文件,例如

Http\\Requests\\Request.php HTTP \\请求\\ Request.php

    <?php namespace App\Http\Requests;

    use Illuminate\Foundation\Http\FormRequest;

    abstract class Request extends FormRequest {

        //

    }

Http\\Requests\\Admin\\PhotoRequest.php 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;
    }

}

What is the purpose of these classes and how does it take effect? 这些课程的目的是什么?它是如何生效的?

You want to have skinny controllers for better maintainability. 您希望拥有瘦控制器以获得更好的可维护性。 When you're having a lot of form fields with a lot of validation rules, your controllers will be bloated. 当您拥有大量具有大量验证规则的表单字段时,您的控制器将变得臃肿。 So you need to move all data logic in models, validation logic in request classes etc. 因此,您需要移动模型中的所有数据逻辑,请求类中的验证逻辑等。

You can read more about single responsibility principle here . 您可以在此处阅读有关单一责任原则的更多信

For example the rules() method, when you submit a form, it will check whether the fields is validated. 例如, rules()方法,当您提交表单时,它将检查字段是否经过验证。 In the controller you can use 在控制器中,您可以使用

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