gpt4 book ai didi

Symfony2 - EventListener 更改 onFlush 数据

转载 作者:行者123 更新时间:2023-12-04 23:02:37 25 4
gpt4 key购买 nike

我正在尝试使用 KnpSnappyBundle 生成 Pdf 并在生成我的比尔实体时保存原则中的位置。

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

我读入了 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 函数,我想在其中保存生成的账单的位置。但我什至不能让它工作。

最佳答案

停止搞乱 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();
}
}
}

关于Symfony2 - EventListener 更改 onFlush 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com