【问题标题】:Laravel 4 Custom Validator throws BadMethodCallExceptionLaravel 4 自定义验证器抛出 BadMethodCallException
【发布时间】:2013-06-04 03:32:02
【问题描述】:

我正在构建我的第一个 Laravel 4 应用程序,并尝试扩展 Validator 类来简单地检查路径是否存在。在official instruction之后,我想出了这个:

app/libraries/CustomValidator.php:

class CustomValidator extends Illuminate\Validation\Validator {
    public function validatePathExists($attribute, $value, $parameters) {
        return is_dir($value);
    }
}

Validator::resolver(function() {
    return new CustomValidator;
});

在控制器中(精简一点):

    $rules = array(
        'path'      => 'required|path_exists',
    );

    $v = Validator::make(Input::get(), $rules); 

此代码引发BadMethodCallException,并带有以下消息:Method [validatePathExists] does not exist.

我已将app/libraries 添加到composer.json 自动加载中:

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

当然是运行composer dump-autoload。事实上,在同一app/libraries 目录下有一个Helper.php,它工作正常。

另外,在app/start/global.php 中(顺便说一句,我不太明白为什么我们必须(?)在两个地方有相同的自动启动寄存器)。

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/libraries',

));

仍然出现错误。任何的想法? 非常感谢您的帮助。

【问题讨论】:

  • 您没有任何依赖项被注入到您的自定义解析器中。再次查看文档。
  • @JosephSilber 不,我什至不认为正在使用自定义解析器。我刚刚注意到依赖项不存在,所以我要从这里开始。
  • @JasonLewis 对不起,我不明白你的意思。我应该补充一点,这是我第一次使用 Laravel。
  • 如果您查看注册解析器时链接到的文档,您需要为您的自定义 Validator 类提供一些依赖项。来自文档:return new CustomValidator($translator, $data, $rules, $messages); 不要忘记将这些变量作为参数包含在您的闭包中。
  • @JasonLewis 实际上我已经尝试将它们添加到相同的例外中:Validator::resolver(function($translator, $data, $rules, $messages) { return new CustomValidator($translator, $data, $rules, $messages); });

标签: php laravel laravel-4


【解决方案1】:

您没有正确注册验证器解析器。

将下面的语法与您的代码进行比较。

Validator::resolver(function($translator, $data, $rules, $messages)
{
    return new CustomValidator($translator, $data, $rules, $messages);
});

【讨论】:

  • 谢谢,但我在上面回答了@JasonLewis,我已经尝试过这种语法但没有成功。
猜你喜欢
  • 2016-11-22
  • 2014-03-30
  • 2014-02-18
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 2013-06-21
相关资源
最近更新 更多