0

我正在研究一个Laravel 应用程序,我在这个应用程序中发现了一些奇怪的行为。

此应用程序中有一些 Web 表单。大多数处理 POST 请求的控制器方法都Validator::make()用于验证用户输入,但我发现有 2 个方法根本不使用Validator::make()

起初我以为这两种形式没有输入验证。然而,令人惊讶的是,我发现 Web 表单仍然能够验证用户输入。

示例 1:( 使用验证器)

  1. 控制器方法 1(第 60 - 67 行)
  2. 控制器方法 2(第 62 - 68 行)

$rules = array(
    'title'   => 'required|min:3',
    'content' => 'required|min:3'
);
...
$validator = Validator::make(Input::all(), $rules);

示例 2:( 不使用验证器)

  1. 控制器方法 3(第 89 - 111 行)
  2. 控制器方法 4(第 27 - 47 行)

$this->user->username = Input::get( 'username' );
$this->user->email = Input::get( 'email' );
$this->user->password = Input::get( 'password' );
...
$this->user->save();

我想知道为什么示例 2中的函数能够在不使用的情况下验证用户输入Validator

4

1 回答 1

2

此应用程序的用户模型使用ConfideUsertrait。如果我们看一下confide包中的那个特性,我们可以看到有一个save()方法可以覆盖 Laravel 的默认方法。

/**
 * Overwrites the original save method in order to perform
 * validation before actually saving the object.
 *
 * @param array $options
 *
 * @return bool
 */
public function save(array $options = array())
{
    if ($this->isValid()) {
        return parent::save($options);
    }
    return false;
}

它会调用$this->isValid()并且只有在一切正常的情况下才会保存。这是isValid()

/**
 * Checks if the current user is valid using the ConfideUserValidator.
 *
 * @return bool
 */
public function isValid()
{
    // Instantiate the Zizaco\Confide\UserValidator and calls the
    // validate method. Feel free to use your own validation
    // class.
    $validator = App::make('confide.user_validator');
    // If the model already exists in the database we call validate with
    // the update ruleset
    if ($this->exists) {
        return $validator->validate($this, 'update');
    }
    return $validator->validate($this);
}

它创建了一个 confide 自己的实例,UserValidator并使用它来验证当前模型。

于 2015-01-14T13:31:20.123 回答