Zend Framework 2: How to get ServiceLocator in validation class

雨燕双飞 提交于 2020-01-02 12:20:29

问题


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?

来源:https://stackoverflow.com/questions/16926000/zend-framework-2-how-to-get-servicelocator-in-validation-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!