在Validator中注入ServiceLocator

时间:2014-09-15 09:43:50

标签: zend-framework2

如何将“普通”ServiceManger注入用于REST调用的自定义验证器(Use without Form)。 ZF 2.2.7用于将外部库的实例注入验证器。

我尝试了以下内容,但没有任何作用:

  • 使用ValidationPluginManager注入它,找不到服务
  • 通过工厂注入,工厂不会加载验证器链
  • 通过验证器选项注入它,这是不可能的,因为“ServiceManager”是ValidationPluginManager的一个实例,其结果如#1所述

有没有任何概念如何解决这个问题,还是我必须放弃并静态链接所有库?

2 个答案:

答案 0 :(得分:1)

关于github的讨论有一个类似的问题here。他们建议使用Zend\Form\FormAbstractServiceFactory并修改那里的依赖关系(weierophinney在关闭主题之前)。

在你的帖子中你提到你没有使用form你的意思是你没有以经典的方式使用表格,或者你是否绕过了整个表格?

如果form存在module.php,我觉得使用验证器似乎不合适。你能详细说明一下吗?

编辑:根据我的理解,zf2要求您的输入过滤器具有类似“输入”的表单元素。等你没有发布任何代码,我根本不知道是否/或你能够以某种方式绕过这个。我仍然不明白你为什么还想在输入过滤器的组合中使用验证器。我只是跳过输入过滤器并编写自定义验证器。

我个人的偏好是在use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use CustomValidator; class CustomValidatorFactory implements FactoryInterface { /** * Create Service Factory * * @param ServiceLocatorInterface $serviceLocator */ public function createService(ServiceLocatorInterface $serviceLocator) { $sm = $serviceLocator->getServiceLocator(); $customService = $sm->get('Application\Service\Geocoding'); $validator= new CustomValidator(); $validator->setCustomService($service); return $validator; } } // CustomValidator.php class CustomValidator extends Zend\Validator\AbstractValidator { public function setCustomService($service) { $this->service = $service; } public function isValid($value) { $customService = $this->service; if ($customService->customMethod() == true) { return true; } return false; } } //module-config.php 'service_manager' => array( 'factories' => array( 'custom\ValidatorFactory' => 'Namespace\To\CustomValidatorFactory', ), ), //yourController or whatever.php will require access to the service manager $customValidation = $sm->get('custom\ValidatorFactory'); // should return true or false now $state = $customValidation->isValid($someValue); 个文件中编写工厂而不是匿名函数。但这也可以采用匿名功能方式。

然后我会简单地解析customValidatorFactory中的依赖项,并在我的控制器或我需要的任何地方获取工厂。

{{1}}

答案 1 :(得分:1)

未经过测试,并且从未使用过ValidationPluginManager但是使用了ControllerManager,FormElementManager等

// GetServiceLocator call should return Instance of ServiceManager
// Then retrieve the service, Yay!
$validationPluginManager->getServiceLocator()->get('SomeService')
相关问题