问题
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