Symfony2 - EventListener更改onFlush上的数据

时间:2013-10-19 21:27:38

标签: symfony doctrine-orm event-listener

我正在尝试使用KnpSnappyBundle生成一个Pdf,并在生成我的比尔实体时将该位置保存在学说中。

我需要那个tamplating服务,我无法进入实体。

我读到了EventListener并尝试让它工作。

我的config.yml

services:
    bill.listener:
        class: MyCompany\CompanyBundle\EventListener\BillListener
        tags:
            - { name: doctrine.event_listener, event: onFlush }

我的听众

namespace MyCompany\CompanyBundle\EventListener;

use Doctrine\ORM\Event\OnFlushEventArgs;

class BillListener
{
    public function onFlush(OnFlushEventArgs $args)
    {
        $em = $args->getEntityManager();
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityInsertions() as $insertions) {
            foreach ($insertions as $entity) {
                if ($entity instanceof Bill) {
                    $entity->setFilename("test.pdf");

                    $md = $em->getClassMetadata(get_class($entity));
                    $uow->recomputeSingleEntityChangeSet($md, $entity);
                }
            }
        }
    }
}

我的Bill Entity有一个setFilename函数,我想保存生成的Bill的位置。但我甚至无法解决这个问题。

1 个答案:

答案 0 :(得分:9)

停止弄乱UOW(这是一种黑客行为),只需再次冲洗它:

<强>配置

services:
    bill.listener:
        class: MyCompany\CompanyBundle\EventListener\BillListener
        arguments: ["@pdf_service"]
        tags :
            - { name: doctrine.event_subscriber, connection: default }

<强>监听

<?php

namespace MyCompany\CompanyBundle\EventListener;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;

use MyCompany\CompanyBundle\Service\MyPDFService;
use MyCompany\CompanyBundle\Entity\Bill;

class BillListener implements EventSubscriber
{
    protected $pdfs;
    protected $bills;

    public function __construct(MyPDFService $pdfs)
    {
        $this->pdfs = $pdfs;
    }

    public function getSubscribedEvents()
    {
        return [
            'onFlush',
            'postFlush'
        ];
    }

    public function onFlush(OnFlushEventArgs $event)
    {
        $this->bills = [];
        /* @var $em \Doctrine\ORM\EntityManager */
        $em = $event->getEntityManager();
        /* @var $uow \Doctrine\ORM\UnitOfWork */
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityInsertions() as $entity) {

            if ($entity instanceof Bill) {

                $this->bills[] = $entity;
            }
        }
    }

    public function postFlush(PostFlushEventArgs $event)
    {
        if (!empty($this->bills)) {

            /* @var $em \Doctrine\ORM\EntityManager */
            $em = $event->getEntityManager();

            foreach ($this->bills as $bill) {

                /* @var $bill \MyCompany\CompanyBundle\Entity\Bill */
                $this->pdfs->generateFor($bill);
                $em->persist($bill);
            }

            $em->flush();
        }
    }
}