Zend Framework 2: How to get ServiceLocator in validation class

Zend框架2:如何在课堂上得到验证servicelocator

问题 (Question)

I would like to get ServiceLocator in my validation class. I tried get it from Controller instance but it returns null.

MyValidation.php  
namespace Register\Validator;

use Zend\Validator\AbstractValidator;
use Register\Controller\RegisterController;

class MyValidation extends AbstractValidator {

    /*
    code...
    */

    function isValid($value)
    {
        $controller = new RegisterController();
        $sm = $controller->getServiceLocator();
        $tableGateway = $sm->get('Register\Model\RegisterTable');
        $tableGateway->myValidationMethod($value);

    }

}

Module.php

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'Register\Model\RegisterTable' =>  function($sm) {
                $tableGateway = $sm->get('RegisterTableGateway');
                $table = new RegisterTable($tableGateway);
                return $table;
            },
            'RegisterTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new RegisterUser());
                return new TableGateway('table-name', $dbAdapter, null, $resultSetPrototype);
            },
        ),
    );
}

But I get Fatal error: Call to a member function get() on a non-object
What is a proper way to get ServiceLocator in model class?

我想我会servicelocator验证类。我试着从控制器实例得到它,但它将返回null。

MyValidation.php  
namespace Register\Validator;

use Zend\Validator\AbstractValidator;
use Register\Controller\RegisterController;

class MyValidation extends AbstractValidator {

    /*
    code...
    */

    function isValid($value)
    {
        $controller = new RegisterController();
        $sm = $controller->getServiceLocator();
        $tableGateway = $sm->get('Register\Model\RegisterTable');
        $tableGateway->myValidationMethod($value);

    }

}

module.php

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'Register\Model\RegisterTable' =>  function($sm) {
                $tableGateway = $sm->get('RegisterTableGateway');
                $table = new RegisterTable($tableGateway);
                return $table;
            },
            'RegisterTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new RegisterUser());
                return new TableGateway('table-name', $dbAdapter, null, $resultSetPrototype);
            },
        ),
    );
}

但我得到的致命错误:调用在非对象的成员函数get()
一种合适的方式在模型类得到servicelocator是什么?

最佳答案 (Best Answer)

You should inject the dependencies of the validator into the validator. You could do that through the options array when you assign the validator to a form field. I wrote up some sample code to demonstrate what I mean:

Register\Validator\MyValidation:

<?php
namespace Application\Validator;

use Zend\Validator\AbstractValidator;

class MyValidation extends AbstractValidator
{
    protected $tableGateway;

    public function __construct($options = null)
    {
        if ($options && is_array($options) && array_key_exists('tableGateway', $options))
        {
            $this->tableGateway = $options['tableGateway'];
        }           
    }

    public function isValid($value)
    {
        // ...
    }
}

As for the form you can either implement the ServiceLocatorAwareInterface, so it gets automatically injected with the service locator, or else inject specific dependencies into the form using a factory for the form.

Here's how you would do it using the ServiceLocatorAwareInterface:

Register\Form\MyForm:

<?php
namespace Register\Form;

use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;

class MyForm extends Form implements InputFilterProviderInterface, ServiceLocatorAwareInterface
{
    protected $servicelocator;

    public function __construct()
    {
        $this->add(array(
                'name' => 'myfield',
                'attributes' => array(
                        'type' => 'text',
                ),
                'options' => array(
                        'label' => 'Field 1'
                ),
            )
        );  
    }

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->servicelocator = $serviceLocator;
    }

    public function getServiceLocator()
    {
        return $this->servicelocator;
    }

    public function getInputFilterSpecification()
    {
        return array(
            'myfield' => array(
                'required'    => true,
                'filters'     => array(),
                'validators'  => array(
                        array(
                            'name'    => 'Application\Validator\MyValidator',
                            'options' => array(
                                'tableGateway'    => $this->getServiceLocator()->get('Application\Model\RegisterTable'),
                            ),
                        ),
                ),
            ),
        );
    }
}

Also it's not clear to me why you are instantiating a Controller in your validator class. You really shouldn't do that.

你应该将验证器的依赖到验证器。你可以通过选项数组赋值时,验证器表单域。我写了一些样本代码来证明我的:

寄存器\ \ myvalidation验证器:

<?php
namespace Application\Validator;

use Zend\Validator\AbstractValidator;

class MyValidation extends AbstractValidator
{
    protected $tableGateway;

    public function __construct($options = null)
    {
        if ($options && is_array($options) && array_key_exists('tableGateway', $options))
        {
            $this->tableGateway = $options['tableGateway'];
        }           
    }

    public function isValid($value)
    {
        // ...
    }
}

至于你可以实现servicelocatorawareinterface形式,所以它会自动注射服务定位器,否则注入特定的依赖关系的形式使用的表厂。

这里是你如何将它应用servicelocatorawareinterface:

寄存器\形式myform:

<?php
namespace Register\Form;

use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;

class MyForm extends Form implements InputFilterProviderInterface, ServiceLocatorAwareInterface
{
    protected $servicelocator;

    public function __construct()
    {
        $this->add(array(
                'name' => 'myfield',
                'attributes' => array(
                        'type' => 'text',
                ),
                'options' => array(
                        'label' => 'Field 1'
                ),
            )
        );  
    }

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->servicelocator = $serviceLocator;
    }

    public function getServiceLocator()
    {
        return $this->servicelocator;
    }

    public function getInputFilterSpecification()
    {
        return array(
            'myfield' => array(
                'required'    => true,
                'filters'     => array(),
                'validators'  => array(
                        array(
                            'name'    => 'Application\Validator\MyValidator',
                            'options' => array(
                                'tableGateway'    => $this->getServiceLocator()->get('Application\Model\RegisterTable'),
                            ),
                        ),
                ),
            ),
        );
    }
}

而且我不清楚为什么你实例化一个控制器在你的验证类。你真的不应该这样做。

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/16926000

相关问题

没有相关问题

相关文章

没有相关文章