zf2:如何从侦听器

时间:2015-09-05 11:59:22

标签: php zend-framework2 zend-validate zfcuser

我正在尝试在新用户(ZfcUser)注册到系统时应用自定义验证程序。验证器应该使用服务。我试图通过工厂注入服务,但看起来工厂中的代码永远不会有机会运行并注入服务。

这是我的代码:

<?php
/**
 * OnlineFieldEvaluation - RegisterFilterListener.php
 *
 * Initial version by: vraskin
 * Initial version created on: 9/3/15
 */

namespace OFEZfcUser\Listener;


use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\Event;


class RegisterFilterListener extends AbstractListenerAggregate {

    public function attach(EventManagerInterface $events)
    {
        $sharedManager = $events->getSharedManager();
        $this->listeners[] = $sharedManager->attach('ZfcUser\Form\RegisterFilter', 'init', array($this, 'onInit'));
    }

    public function onInit(Event $e)
    {

        $filter = $e->getTarget();

        $filter->add(array(
            'name' => 'email',
            'required' => true,
            'validators' => array(
                array(
                    'name' => 'OFEZfcUser\Validators\OFEtoSFEmailValidator',
                    'options' => null,
                ),
            ),
        ));
    }

} 

Module.php

     public function getValidatorConfig() {
        return array(
//            'invokables' => array(
//                'OFEZfcUser\Validators\OFEtoSFEmailValidator' => 'OFEZfcUser\Validators\OFEtoSFEmailValidator'
//            ),
            'factories' => array(
//                'OFEZfcUser\Validators\OFEtoSFEmailValidator' => 'OFEZfcUser\Factories\OFEValidatorFactory',

                'OFEZfcUser\Validators\OFEtoSFEmailValidator' =>  function ($serviceManager) {
                    $ofeService =  $serviceManager->getServiceLocator()->get('OFEClientForRestSalesforceAPIService');
                    $ofeValidator = new \OFEZfcUser\Validators\OFEtoSFEmailValidator();
                    $ofeValidator->setOFEService($ofeService);

                    return $ofeValidator;
                }

            )
        );
    }

验证

  <?php

namespace OFEZfcUser\Validators;

use Zend\Validator\AbstractValidator;

class OFEtoSFEmailValidator extends AbstractValidator{

    const NOTSFEMAIL = 'NOTSFEMAIL';

    protected $messageTemplates = array(
        self::NOTSFEMAIL => 'This user is not registered in our system. Please, contact a field administration',
    );

    protected $service;

    public function __construct(array $options = array()){
        parent::__construct($options);
    }

    public function isValid($value,$context = null){
        $this->setValue($value);
        if (!$this->validateSFEmail($value, $context['userRole'])) {
            $this->error(self::NOTURL);
            return false;
        }
        return true;
    }

    private function validateSFEmail($email, $userRole) {

    echo $this->service->greet();

    $sfRes = $this->service->isStudentExist($email, $userRole);

    var_dump( $sfRes );


    if ($sfRes != true && $sfRes != false ) {
        return false;
    } else {
        return $sfRes;
    }
}

    public function setOFEService($service)
    {
        $this->service = $service;
    }

} 

这是我得到的错误:$ this-&gt; service等于null,在我看不到它正在调用Factory代码。但验证器会以某种方式实例化。

  

致命错误:在第50行的C:\ dev \ projects \ OnlineFieldEvaluation \ module \ OnlineFieldEvaluation \ src \ OFEZfcUser \ Validators \ OFEtoSFEmailValidator.php中的非对象上调用成员函数greet()

enter image description here

编辑2

我还尝试使用validator \ Callable来调用验证器工厂,因此它可以将服务注入验证器实例。但工厂从未被发现过。

Module.php

 public function getValidatorConfig()
{
    return [
        'factories' => [
            'OFEtoSFEmailValidator' => function ($serviceManager) {
                $ofeService = $serviceManager->getServiceLocator()->get('OFEClientForRestSalesforceAPIService');
                $ofeValidator = new \OFEZfcUser\Validators\OFEtoSFEmailValidator(['service' => $ofeService]);

                return $ofeValidator;
            }

        ]
    ];
}

然后我尝试使用Validator \ Callable

从RegisterFileterListener实例化它
  namespace OFEZfcUser\Listener;

use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\Event;


class RegisterFilterListener extends AbstractListenerAggregate
{

    public function attach(EventManagerInterface $events)
    {
        $sharedManager = $events->getSharedManager();
        $this->listeners[] = $sharedManager->attach('ZfcUser\Form\RegisterFilter', 'init', array($this, 'onInit'));
    }

    public function onInit(Event $e)
    {
        $filter = $e->getTarget();

        $valid = new \Zend\Validator\Callback('OFEtoSFEmailValidator');

        $validators = $filter->get('email')->getValidatorChain();

        $factory = new \OFEZfcUser\Factories\OFEValidatorFactory();

        $filter->add(array(
            'name' => 'email',
            'required' => true,
            'validators' => array(
                array(
                    'name' => 'Callback',
                    'options' => array(
                        'messages' => array(
                            \Zend\Validator\Callback::INVALID_VALUE => 'My custom message',
                            \Zend\Validator\Callback::INVALID_CALLBACK => 'My custom message'
                        ),
                        'callback' => array($factory, 'createService')
                    )
                ),
            ),
        ));
    }

} 

1 个答案:

答案 0 :(得分:0)

我放弃了尝试从过滤器上的侦听器调用验证器工厂。我从ZfcUser复制了RegisterFilter,并修改了它的构造函数以接受第三个验证器。然后我从module.config.php文件中调用了验证器工厂,并将其注入我的自定义过滤器。

    'service_manager' => array(

        'factories' => array(
            'zfcuser_register_form' => function ($sm) {
                $options = $sm->get('zfcuser_module_options');
                $validators = $sm->get('ValidatorManager');
                $ofeVal = $validators->get('MyOFEtoSFEmailValidator');

                $registerFilter = new ZfcUserRegisterFilterExtension(
                    new Validator\NoRecordExists(array(
                        'mapper' => $sm->get('zfcuser_user_mapper'),
                        'key' => 'email'
                    )),
                    new Validator\NoRecordExists(array(
                        'mapper' => $sm->get('zfcuser_user_mapper'),
                        'key' => 'username'
                    )),
//                    My custom Validator to connect to SF and validate email
                    $ofeVal,
                    $options
                );

                $form = new \OFEZfcUser\Form\ZfcUserRegisterExtension(null, $options);

                $form->setInputFilter($registerFilter);

                return $form;
            },

        )),