Laravel一起使用Policies和FormRequest类

时间:2016-03-04 11:49:13

标签: php laravel laravel-5 laravel-authorization

我使用Form Request类来验证传入控制器的数据。

此外,我还使用Policies来确定当前用户是否被允许show / update / destroy等相关对象。

如果我使用的是政策,这是否意味着我可以简单地使用:

public function authorize()
{
    return true;
}

在我的Request类中?或者我应该做两次检查/以不同的方式写它们?

如果有人能够对此有所了解,那就太棒了。

感谢。

1 个答案:

答案 0 :(得分:0)

参见\ Illuminate \ Validation \ ValidatesWhenResolvedTrait

<?php

namespace Illuminate\Validation;

use Illuminate\Contracts\Validation\ValidationException;
use Illuminate\Contracts\Validation\UnauthorizedException;

/**
 * Provides default implementation of ValidatesWhenResolved contract.
 */
trait ValidatesWhenResolvedTrait
{
    /**
     * Validate the class instance.
     *
     * @return void
     */
    public function validate()
    {
        $instance = $this->getValidatorInstance();

        if (! $this->passesAuthorization()) {
            $this->failedAuthorization();
        } elseif (! $instance->passes()) {
            $this->failedValidation($instance);
        }
    }

    /**
     * Get the validator instance for the request.
     *
     * @return \Illuminate\Validation\Validator
     */
    protected function getValidatorInstance()
    {
        return $this->validator();
    }

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return mixed
     */
    protected function failedValidation(Validator $validator)
    {
        throw new ValidationException($validator);
    }

    /**
     * Determine if the request passes the authorization check.
     *
     * @return bool
     */
    protected function passesAuthorization()
    {
        if (method_exists($this, 'authorize')) {
            return $this->authorize();
        }

        return true;
    }

    /**
     * Handle a failed authorization attempt.
     *
     * @return mixed
     */
    protected function failedAuthorization()
    {
        throw new UnauthorizedException;
    }
}

和\ Illuminate \ Foundation \ Http \ FormRequest

/**
 * Determine if the request passes the authorization check.
 *
 * @return bool
 */
protected function passesAuthorization()
{
    if (method_exists($this, 'authorize')) {
        return $this->container->call([$this, 'authorize']);
    }

    return false;
}

它仅检查返回的结果,并确定在请求解决时是否继续。它没有通过策略或任何中间件或某事。很奇怪。