简体   繁体   English

您如何通过粉刺注入Valitron并重复使用

[英]How do you Inject Valitron with Pimple and reuse

So I've been using the Valitron Library to validate posted forms mostly and have run into some issues. 因此,我一直在使用Valitron库来验证张贴的表单,并且遇到了一些问题。

The constructor accepts the data to be validated and this causes problems when you inject the library as a dependency with Pimple or some other container. 构造函数接受要验证的数据,这会在您将库作为对Pimple或其他容器的依赖项注入时引起问题。 It also causes issues if you want to validate multiple things, as you basically have to instantiate the library every time you want to use it. 如果您要验证多件事情,也会引起问题,因为基本上每次使用该库时都必须实例化该库。

Is there some way around this? 有办法解决吗?

Ultimately I would like to be able to define the library as a service and inject it with Pimple like this: 最终,我希望能够将库定义为服务,并将其注入Pimple,如下所示:

$container['Valitron'] = function(){
    return new \Valitron\Validator();
};

Any controller/class that needs to validate something would initialise it in their constructor like this: 任何需要验证某些内容的控制器/类都可以在其构造函数中将其初始化,如下所示:

public function __construct($valitron)
{
    $this->valitron = $valitron;
}

Any time I need to validate something I could say something like: 每当我需要验证某些内容时,我都可以说:

// First use
$this->valitron->setData($_POST);
$this->valitron->rule('required', 'name')->message('Im required')->label('Name');
$this->valitron->validate();

// Second use
$this->valitron->setData($_GET);
$this->valitron->rule('required', 'test')->message('Im also required')->label('Test');
$this->valitron->validate();

But there doesn't seem to be a setData function, or any way to reset the library between usages. 但是似乎没有setData函数,也没有任何在使用之间重置库的方法。

Question: How do I use Valitron with Pimple and reuse it for validating multiple things at a time? 问题:如何将Valitron与Pimple结合使用,并重新使用它一次验证多个事物?

Please Note: It must be injected. 请注意:必须注射。 It also should not need to be initialised before each usage. 每次使用前也不必初始化它。 Please don't tell me I have to extend the library or hack it to make it work properly! 请不要告诉我,我必须扩展库或修改它才能使其正常工作!

Came across your question when I was searching for the same as you did bit I came also across the following Github issue in Valitron's repo, see https://github.com/vlucas/valitron/issues/108 当我搜索与您搜索的相同内容时遇到了您的问题,我也遇到了Valitron回购中的以下Github问题,请参阅https://github.com/vlucas/valitron/issues/108

vlucas wrote: Valitron is currently designed to be a one-use instance, so it could lead to weird things like custom labels and error messages not getting reset between validations (because it was never meant to be used that way). vlucas写道:Valitron目前被设计为一次性使用的实例,因此它可能导致自定义标签和错误消息之类的怪异事情在验证之间无法重置(因为它从未打算以这种方式使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM