0

所以我一直在使用 Valitron 库来验证发布的表单,并且遇到了一些问题。

构造函数接受要验证的数据,当您将库作为 Pimple 或其他容器的依赖项注入时,这会导致问题。如果你想验证多个东西,它也会导致问题,因为你基本上每次想要使用它时都必须实例化库。

有没有办法解决这个问题?

最终,我希望能够将库定义为服务并像这样用 Pimple 注入它:

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

任何需要验证某些东西的控制器/类都会在它们的构造函数中初始化它,如下所示:

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

每当我需要验证某些内容时,我都可以说:

// 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();

但似乎没有 setData 函数,或任何在使用之间重置库的方法。

问题:我如何将 Valitron 与 Pimple 一起使用并重用它来一次验证多个事物?

请注意:必须注入。它也不应该需要在每次使用之前进行初始化。请不要告诉我我必须扩展库或破解它才能使其正常工作!

4

1 回答 1

2

当我在搜索与您相同的问题时遇到了您的问题,我还在 Valitron 的仓库中遇到了以下 Github 问题,请参阅https://github.com/vlucas/valitron/issues/108

vlucas 写道: Valitron 目前被设计为一次性实例,因此它可能会导致奇怪的事情,例如自定义标签和错误消息在验证之间没有被重置(因为它从来没有打算以这种方式使用)。

于 2016-03-16T08:19:15.063 回答