我正在寻找我在表单上设置的验证器的配置。通常情况下,我可以向服务经理提出此请求,但我不清楚如何从一个验证器的深入处理,然后将在表单上使用。
我到目前为止的骨架代码是:
<?php
namespace Application\Validator;
use Zend\Validator\AbstractValidator;
use Auth\Model\LdapAdapter;
class MyAccount extends AbstractValidator
{
const INVALID_ACCOUNT = 'invalid_account';
protected $messageTemplates = array(
self::INVALID_ACCOUNT => "'%value%' does not appear to be a valid account."
);
public function isValid($value)
{
$this->setValue($value);
// What I'd like to get:
$ldapConfig = $this->getServiceLocator()->get('Config')['ldap'];
$ldapAdapter = new LdapAdapter($ldapConfig['server'],
$ldapConfig['backup_server'],
$ldapConfig['bind_dn'],
$ldapConfig['bind_password'],
$ldapConfig['search_dn']);
$result = $ldapAdapter->getInfoForUser('sampleUsername');
// do something with the result and then return
return true;
}
}
答案 0 :(得分:1)
您的验证器取决于配置的LDAP适配器。为验证器创建一个工厂,通过从服务管理器请求它或自己创建它来检索所需的适配器。
namespace Application\Factory\Adapter;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Auth\Model\LdapAdapter;
class AccountValidator implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
// create configured LDAP adapter
$ldapConfig = $serviceLocator->get('Config')['ldap'];
$ldapAdapter = new LdapAdapter(
$ldapConfig['server'],
$ldapConfig['backup_server'],
$ldapConfig['bind_dn'],
$ldapConfig['bind_password'],
$ldapConfig['search_dn']
);
// create validator
$validator = new \Application\Validator\AccountValidator();
// inject LDAP adapter dependency
$validator->setLdapAdapter($ldapAdapter);
return $validator;
}
}
在这种情况下,工厂使用setter注入已配置的LDAP适配器。在验证器类中创建此setter,该类在属性中存储指向适配器的指针,以便稍后在isValid
方法中使用。
不要忘记将工厂添加到模块配置中:
[...]
'validators' => [
'factories' => [
'account' => 'Application\Factory\Adapter\AccountValidator',
],
],
确保从服务管理器中检索验证器,以便工厂启动。creating a form via factory,factory-backed form extension等等,它会为您完成。
进一步阅读:依赖注入的概念,Service Manager