4

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

为此,我需要打版服务,但我无法进入实体。

我读了 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);
                }
            }
        }
    }
}

我的账单实体有一个 setFilename 函数,我想在其中保存生成的账单的位置。但我什至不能让它工作。

4

1 回答 1

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();
        }
    }
}
于 2013-10-20T22:59:42.757 回答