Symfony事件监听器

时间:2016-06-14 09:57:51

标签: php symfony doctrine-orm listener

您好我要按照此文档执行Symfony事件侦听器: http://symfony.com/doc/2.8/cookbook/doctrine/event_listeners_subscribers.html

<?php

namespace FM\AppBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use FM\AdminBundle\Entity\Address\BillingAddress;

class BillingAdressListener
{
    /**
     * @param LifecycleEventArgs $args
     */
    public function listenBillingAdress(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if(!$entity instanceof BillingAddress){
            return;
        }

        $this->postPersist($args);
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        $em = $args->getEntityManager();
        $billingAdress = $args->getEntity();

        dump($billingAdress); die();
    }
}

service.yml

billing_adress.listener:
        class: FM\AppBundle\EventListener\BillingAdressListener
        tags:
            - { name: doctrine.event_listener, event: listenBillingAdress }

但是当我使用 BillingAddress 对象提交表单时,没有任何事情发生。

我做错了吗?

2 个答案:

答案 0 :(得分:0)

它在Doctrine中称为实体监听器。这是documentation

不要忘记在映射中添加您的实体侦听器。例如xml映射:

<entity name="AppBundle\Entity\AssignmentAttempt" table="app_assignment_attempt" >
    <entity-listeners>
        <entity-listener class="AppBundle\EntityListener\AssignmentAttemptListener">
            <lifecycle-callback type="prePersist" method="prePersist"/>
            <lifecycle-callback type="preUpdate" method="preUpdate"/>
        </entity-listener>
    </entity-listeners>
    <!-- Rest mapping -->
</entity>

在配置中,您只需添加

即可
app.entity_listener.assignment_attempt:
     class: AppBundle\EntityListener\AssignmentAttemptListener
     tags:
         - { name: doctrine.orm.entity_listener }

答案 1 :(得分:0)

我的不好,我没有做坚持,而是更新

适用于持久

现在是我的代码:

<?php

namespace FM\AppBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use FM\AdminBundle\Entity\Address\BillingAddress;

class BillingAddressListener
{
    /**
     * @param LifecycleEventArgs $args
     */
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if(!$entity instanceof BillingAddress){
            return;
        }

        $this->addNameToUser($args);
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function addNameToUser(LifecycleEventArgs $args)
    {
        /** @var BillingAddress $billingAdress */
        $billingAdress = $args->getEntity();
        $user = $billingAdress->getOwner();

        if(empty($user->getFirstName())) $user->setFirstName($billingAdress->getFirstName());
        if(empty($user->getLastName())) $user->setLastName($billingAdress->getLastName());
    }
}

我必须调用prePersist方法。 我正在做相反的事情。

billing_address.listener:
    class: FM\AppBundle\EventListener\BillingAddressListener
    tags:
        - { name: doctrine.event_listener, event: prePersist }