1

我一直在扩展 ZfcUser 我让新字段正常工作,并且它们正在通过学​​说 2 添加到数据库中,没有问题。但现在我需要在用户和支付表和特殊角色系统之间添加一个链接。我试图将其放入事件中,但我无法保留教义服务。我的 onBootstrap 看起来像这样。

public function onBootstrap( MVCEvent $e )
{
    $eventManager = $e->getApplication()->getEventManager();
    $em           = $eventManager->getSharedManager();
    $em->attach(
        'ZfcUser\Form\RegisterFilter',
        'init',
        function( $e )
        {
            $filter = $e->getTarget();

            // do your form filtering here 
            new Register\Filter($filter);

        }
    );

    // custom form fields

    $em->attach(
        'ZfcUser\Form\Register',
        'init',
        function($e)
        {
            /* @var $form \ZfcUser\Form\Register */
            $form = $e->getTarget();
            new Register\Form($form);
        }
    );

    // here's the storage bit

    $zfcServiceEvents = $e->getApplication()->getServiceManager()->get('zfcuser_user_service')->getEventManager();
    $doctrineObjectManager = $e->getApplication()->getServiceManager()->get('Doctrine\ORM\EntityManager');
    var_dump($e->getApplication()->getServiceManager()->get('zfcuser_user_service')->getEventManager()->getEvents()); 
    $zfcServiceEvents->attach('register', function($e){
        /* @var $user \User\Entity\User */
        //$form = $e->getParam('form');
        //print_r($form);
        //echo get_class($e);
        new Register\Storage($e);
        break;
    });

    // you can even do stuff after it stores           
    $zfcServiceEvents->attach('register.post', function($e) {
        /*$user = $e->getParam('user');*/
    });
}

表单和过滤器有效,但我无法从匿名事件函数中访问 docrtine 服务。我该怎么做呢?

4

1 回答 1

3

由于您正在执行此操作,onBootstrap()因此MvcEvent拥有您需要的一切。您只需要use在匿名函数中获取实体管理器及其

public function onBootstrap( MVCEvent $e )
{
    $eventManager = $e->getApplication()->getEventManager();
    $em           = $eventManager->getSharedManager();
    // fetch the entity manager
    $sm = $e->getApplication()->getServiceManager();
    $entityManager = $sm->get('Doctrine\ORM\EntityManager');

    $em->attach(
        'ZfcUser\Form\RegisterFilter',
        'init',
        // use the entity manager in your function
        function( $e ) use ($entityManager);
        {
            $filter = $e->getTarget();

            // variable $entityManager is now available in this scope
            // so we could for example inject it into the filter like so
            new Register\Filter($filter, $entityManager);                

        }
    );

我假设实体管理器是您所指的原则服务,但它与use您的匿名函数范围内的其他服务的方法相同。

于 2013-06-09T21:41:55.773 回答