【发布时间】: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() 的行为。
我错过了什么,我怎样才能做到这一点?
【问题讨论】:
-
你看@这个 L4 的 SO 答案了吗? stackoverflow.com/q/18161785/1317935
-
@TheShiftExchange 我怎么会错过这个?!谢谢,完美无缺!
标签: php validation laravel laravel-4