【问题标题】:Laravel 4 Form Validation, Extending the __call() methodLaravel 4 表单验证,扩展 __call() 方法
【发布时间】:2013-09-24 12:27:34
【问题描述】:

我想扩展表单验证类以支持数组表单元素,如 L4 中描述的here for L3

首先,我在我的app/config/app.php 中更改了验证器别名:

'Validator'       => 'app\lib\Support\Facades\Validator',

然后,我将这些代码保存为 app/lib/Support/Facades/Validator.php

<?php namespace app\lib\Support\Facades;


class Validator extends \Illuminate\Support\Facades\Validator {

    public function __call($method, $parameters) {

      if (substr($method, -6) === '_array') {

          $method = substr($method, 0, -6);
          $values = $parameters[1];
          $success = true;
          foreach ($values as $value) {
              $parameters[1] = $value;


              $rule = snake_case(substr($method, 8));

                if (isset($this->extensions[$rule]))
                {
                    $success &= $this->callExtension($rule, $parameters);
                }

                throw new \BadMethodCallException("Method [$method] does not exist.");
          }
          return $success;
      } else {
          return parent::__call($method, $parameters);
      }

    }

    protected function getMessage($attribute, $rule) {

        if (substr($rule, -6) === '_array') {
          $rule = substr($rule, 0, -6);
        }

        return parent::getMessage($attribute, $rule);
    }

}

然后我确保我的composer.json 包含用于自动加载的文件夹:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",

        "app/lib",
        "app/lib/Support",
        "app/lib/Support/Facades"
    ]
},

然后,我运行php composer.phar dump-autoload 来生成自动加载类。

问题是,这似乎不起作用。我什至尝试在生成的文件中添加自定义验证方法,如下所示:

protected function validateTest($attribute, $value) {
    return $value=='test';
}

上面写着:Method [validateTest] does not exist.。我把protected改成了public,还是一样。

get_class(Validator::getFacadeRoot()) 给了我\Illuminate\Validation\Factory,但是当我扩展我写给它的类时,我得到了这个错误:Non-static method Illuminate\Validation\Factory::make() should not be called statically

注意:是的,我没有像 L4 方式那样扩展规则,因为我不想添加新规则,但我想更改 __call() 的方法和getMessage() 的行为。

我错过了什么,我怎样才能做到这一点?

【问题讨论】:

标签: php validation laravel laravel-4


【解决方案1】:

看来我搜索的不够多。正如 cmets 中所建议的,我只是将共享的代码 in this answer 添加到我的 app/routes.php 中,而没有创建新文件或更改别名,它完美地工作!

这是我在解决方案中给出的验证规则:

$rules = array(
    'items'     => 'required|min:1|integerOrArray'
);

【讨论】:

    猜你喜欢
    • 2014-11-06
    • 2015-07-19
    • 1970-01-01
    • 2015-03-27
    • 2013-12-07
    • 1970-01-01
    • 2018-11-13
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多