php - 在 Controller 中验证

标签 php validation unit-testing laravel

我是 Laravel 的新手,我需要一些帮助来重构我的代码。 现在,方法未在 100% 的测试中涵盖,因为我无法模拟验证器对象及其响应。 我的 Controller 中有以下方法

public function store(Request $request)
{
    $data = $request->only([
        'name',
        'email',
        'message',
    ]);

    $validator = Validator::make($data, $this->validatorRules);

    if ($validator->fails()) {
        return $this->response->errorFromValidator($validator);
    }

    $savedItem = $this->repository->store($data);

    if (!$savedItem) {
        return $this->response->error('Cannot save');
    }

    return $this->response->succesItem($savedItem);
}

我试图在 Controller 的构造函数中注入(inject)验证器:

function __construct(Response $response, Repository $repository, Validator $validator)
{
    $this->response = $response;
    $this->repository = $repository;
    $this->validator= $validator;
}

并在方法中使用它:

$this->validator::make($data, $this->validatorRules);

但我收到语法错误,意外的“::”(T_PAAMAYIM_NEKUDOTAYIM)。 我如何在方法之外抽象验证器,以便在测试中模拟验证器?

最佳答案

为什么要使用 Validator 来验证数据?

  • 使用 Request 将使您的 Controller 保持干净和最小化。但一些 在 Controller 中使用 Validator 是明智的,例如你知道 将只有一个字段需要验证,那么它将是 过度使用 FormRequest。所以这是一个偏好问题。
  • 请求类是验证请求的更好方法,因为它们 有助于从构造方法中提取此功能,该方法 应该尽可能干净。

我建议您使用 Requests 来验证您的表单数据,而不是在您的 Controller 中使用 Validator。从您的代码中我可以注意到您正在尝试保存联系表格,所以这里是我的建议:

运行此命令,这将在“Requests”文件夹中创建一个 ContactRequest 文件:

php artisan make:request ContactRequest

联系请求文件:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|min:5|max:20|alpha',
            'email' => 'required|email',
            'message' => 'required|max:250'
        ];
    }
}

注意:您必须将 autorize 设置为 return true; 以避免未授权错误。

你的 Controller :

<?php namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;

class ContactController extends Controller {

function __construct(Repository $repository)
{
    $this->repository = $repository;
}

public function store(ContactRequest $request)
{
    return $this->repository->store($data);
}

}

在您的 View 文件中,您可以像这样处理错误:

    @if (count($errors) > 0)
        <div class="alert alert-danger">
        <button class="close" data-close="alert"></button>
                @foreach ($errors->all() as $error)
                    <span>{{ $error }}</span>
                @endforeach
        </div>
    @endif

或者,如果您更喜欢一个一个地显示错误,您可以这样做:

{!! $errors->first('name', '<small class="help-block">:message</small>') !!}
{!! $errors->first('email', '<small class="help-block">:message</small>') !!}
{!! $errors->first('message', '<small class="help-block">:message</small>') !!}

只有当数据通过 ContactRequest 验证时,您的数据才会被存储。

现在您的方法应该包含在测试中,您可以注意到您的 Controller 变得多么干净。

关于php - 在 Controller 中验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31490502/

相关文章:

php - 如果 laravel eloquent 中请求变量为 null,则不要更改 mysql 列值

php - NodeJS 如何对 Buffer 进行哈希处理?

c++ - 如何有效地将 if 和 else 用于过滤结构?

php - Drupal 表单验证对我不起作用

swift - 找不到 Find : Elements matching predicate '""IN identifiers' from input 的匹配项

javascript - 单击提交按钮时,php session 不适用于表单

php - 从 PHP 脚本获取 XMLHttpRequest 进度

ruby-on-rails - Rails 在每个字段下方显示表单错误

mysql - 测试时的 CakePHP 连接

c# - 在单元测试中输出文本