如何访问Validator :: extend中的其他输入属性? [英] How to access other input attributes in Validator::extend?

查看:322
本文介绍了如何访问Validator :: extend中的其他输入属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题标题指出: 使用Validator :: extend时如何访问其他输入属性?

As the question title states: How can you access other input attributes when using Validator::extend?

检查Laravel的内置Validator类后,可以看到它使用$this->data访问其他属性;但是您不能在Validator :: extend要求的闭包中直接使用$this.

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 $thisin the closure that Validator::extend requires.

似乎(通过自定义类)手动扩展Validator类是唯一的选择...我正确吗?如果是这样,对我来说,这似乎是将验证器转换为程序包的一个严重限制,因为每个程序包都会扩展基本的Validator类,PHP最终将为其保留最后定义的扩展(从而使其他验证程序包不可用...).还是我错过了什么?

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?

谢谢.

编辑

我还尝试将其包装在Jason Lewis的此方法之后的程序包中,但我不断收到BadMethodCallException声明找不到验证方法...该程序包符合psr-0,而且我很确定这不是命名空间问题.

I also tried to wrap it up in a package following this method by 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.

推荐答案

经过一些测试,如果您使用类而不是回调,则可以访问数组.随着它扩展Validator类.

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.

class TestRulesValidator extends \Illuminate\Validation\Validator
{

    public function validateTestRule($attribute, $value, $parameters)
    {
        var_dump($this->data);

        exit();
    }

}

验证文档中,使用:

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

您的规则名称将为test_rule.删除validate关键字并转换为下划线大小写.

Your rule name would be test_rule. Remove the validate keyword and convert to underscore case.

只需在全新安装上对其进行测试即可,并且可以正常工作.

Just tested this on fresh installation and it works.

编辑-您还可以使用常规的extend方法并传递一个额外的参数.

Edit - You can also use the normal extend method and pass an extra parameter.

class TestRulesValidator
{

    public function validateTestRule($attribute, $value, $params, $validator) {
        var_dump($validator->getData());
    }

}

Validator::extend('test_rule', 'TestRulesValidator@validateTestRule');

这篇关于如何访问Validator :: extend中的其他输入属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆