如何将 ServiceLocator 注入验证器?

Ho do I Inject ServiceLocator into validator?

我为我的一个表单域创建了一个验证器。为此,我需要 ServiceLocator,所以我想使用工厂 ...

编辑:

这是我的工厂:

namespace Maintenance\Factory\Validator;

/* Zend */
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/* Controller */
use Maintenance\Validator\Echeancedebut;

class EcheancedebutFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $realServiceLocator = $serviceLocator->getServiceLocator();

        $maiContratService = $realServiceLocator->get(
            'Maintenance\Service\Model\FMaiContratService'
        );

        return new Echeancedebut($maiContratService);
    }
}

我的验证器:

class Echeancedebut extends AbstractValidator
{
    const ERROR_DATEDEB = 'ERROR_DATEDEB';

    protected $maiContratService;

    protected $messageTemplates = array(
        self::ERROR_DATEDEB => "Saisie inférieure à la date de début du contrat"
    );

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

    public function isValid($value){
        $this->setValue($value);
        if (!$this->validatedate($value)) {
            $this->error(self::ERROR_DATEDEB);
            return false;
        } 
        return true;
    }

    private function validatedate($date) {
        return false;
    }
}

编辑:

我的输入过滤器:

public function getInputFilter()
{
    if (! $this->inputFilter) {
        $inputFilter = new InputFilter();
        $this->inputFilter = $inputFilter;
    }

    $inputFilter->add(
        array(
            'name' => 'dateDeb',
            'required' => true,
            'allow_empty' => false,
            'validators' => array(
                array(
                    'name' => 'Date',
                    'locale' => 'FR_fr',
                    'options' => array(
                        'format' => 'd/m/Y',
                    ),
                ),
                array(
                    'name' => 'Maintenance\Validator\Echeancedebut',
                    'options' => array(
                        'contratId' => $this->iMaiContratId,
                    )
                );

                return $this->inputFilter;
}

问题是它没有检索到我的错误消息,为什么?

您的工厂名称与您在配置中注册的名称不对应:

Maintenance\Factory\Validator\EcheancedebutFactory(在您的配置中)

Maintenance\Factory\Validator\EcheancedebFactory(class 全名)

Echeancedebut 对比 Echeancedeb.

改变它,我认为它应该有效。

好的,所以在验证器中注入 Sl 是个坏主意。我将通过我的控制器调用的 inputFilter 将我的选项作为参数传递。这样问题就解决了。感谢您的回答。