laravel 如何访问 Validator::extend 中的其他输入属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22491088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access other input attributes in Validator::extend?
提问by Propaganistas
As the question title states: How can you access other input attributes when using Validator::extend?
正如问题标题所述:使用 Validator::extend 时如何访问其他输入属性?
Upon inspecting Laravel's built-in Validator class, I can see it uses $this->data
to access other attributes; however you can't directly use $this
in the closure that Validator::extend requires.
在检查 Laravel 的内置 Validator 类时,我可以看到它用于$this->data
访问其他属性;但是你不能直接$this
在 Validator::extend 需要的闭包中使用。
It seems like manually extending the Validator class (through a custom class) is the only option... Am I correct? If so, this seems to me like a serious limitation for converting validators into packages as each package would extend the base Validator class for which PHP would eventually just retains the last defined extension (and thus rendering other validator packages unusable...). Or am I missing something?
似乎手动扩展 Validator 类(通过自定义类)是唯一的选择......我对吗?如果是这样,在我看来,这对于将验证器转换为包是一个严重的限制,因为每个包都会扩展基本的 Validator 类,PHP 最终将只保留最后定义的扩展(从而使其他验证器包无法使用......)。或者我错过了什么?
Thanks.
谢谢。
EDIT
编辑
I also tried to wrap it up in a package following this methodby Jason Lewis but I keep getting a BadMethodCallException
stating that the validation method could not be found... The package is psr-0 compliant and I'm pretty sure it's not a namespacing issue.
我还尝试按照Jason Lewis 的这种方法将它包装在一个包中,但我不断收到一条BadMethodCallException
声明,指出无法找到验证方法......该包符合 psr-0,我很确定它不是命名空间问题。
回答by SamV
After a bit of testing, you can access the array if you use a class and not a callback. As it extends the Validator
class.
经过一些测试,如果您使用类而不是回调,则可以访问该数组。因为它扩展了Validator
类。
class TestRulesValidator extends \Illuminate\Validation\Validator
{
public function validateTestRule($attribute, $value, $parameters)
{
var_dump($this->data);
exit();
}
}
From the validation documentation, use:
从验证文档中,使用:
Validator::resolver(function($translator, $data, $rules, $messages) {
return new TestRulesValidator($translator, $data, $rules, $messages);
});
Your rule name would be test_rule
. Remove the validate
keyword and convert to underscore case.
您的规则名称将是test_rule
. 删除validate
关键字并转换为下划线大小写。
Just tested this on fresh installation and it works.
刚刚在全新安装上进行了测试,并且可以正常工作。
Edit- You can also use the normal extend
method and pass an extra parameter.
编辑- 您也可以使用普通extend
方法并传递额外的参数。
class TestRulesValidator
{
public function validateTestRule($attribute, $value, $params, $validator) {
var_dump($validator->getData());
}
}
Validator::extend('test_rule', 'TestRulesValidator@validateTestRule');