我想在我的验证类中获得 ServiceLocator。我尝试从 Controller 实例中获取它,但它返回 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);
}
}
模块.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 的正确方法是什么?