代码之家  ›  专栏  ›  技术社区  ›  Loïc Pennamen

为什么这个Doctrine EntityListener在Symfony6中不起作用?

  •  0
  • Loïc Pennamen  · 技术社区  · 2 年前

    在Symfony 6.3上,我使用这个基于监听器的 on the documentation 。它在保存实体之前计算附加数据:

    <?php
    namespace App\EventListener;
    
    use App\Entity\Simulation;
    use App\Goflex\Simulator;
    use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
    use Doctrine\ORM\Events;
    
    #[AsEntityListener(event: Events::preUpdate, method: 'consolidate', entity: Simulation::class)]
    class SimulationConsolidator
    {
        private function consolidate(Simulation $simulation, $event): void
        {
            // for debugging purpose
            throw new \Exception("test"); 
            // My logic...
            $simulation->setXxxxx();
        }
    }
    

    控制器按预期工作-即它确实保存了我的实体:

    // ...
    class SimulationController extends AbstractController
    {
        // ...
        public function save(Simulation $simulation, Request $request, EntityManagerInterface $em): Response
        {
            $success = true;
            $errorMsg = null;
    
            try {
                $form = $this->createForm(SimulationType::class, $simulation);
                $form->handleRequest($request);
                if ($form->isSubmitted()) {
                    if(true !== $form->isValid()) {
                        foreach($form->getErrors(true) as $error) {
                            $errorMsg .= $error->getMessage()."\n";
                        }
                    }
                    else {
                        $em->persist($simulation);
                        $em->flush();
                    }
                }
            } catch (\Exception $exception) {
                $success = false;
                $errorMsg = $exception->getMessage();
            }
    
            return $this->json([
                'success' => $success,
                'errorMsg' => $errorMsg,
            ]);
        }
    

    我尝试在services.yaml中声明侦听器:

    services:
        App\EventListener\SimulationConsolidator:
            tags:
                -
                    name: 'doctrine.orm.entity_listener'
                    event: 'preUpdate'
                    entity: 'App\Entity\Simulation'
                    method: 'consolidate'
    
    

    有趣的是,出现了这个错误:
    “App\Entity\Simulation”中的实体侦听器“App\EventListener\SimulationConsolidator#consolidate()”已声明,但只能声明一次。

    这意味着我的倾听者 已声明,但从未触发。我“应该”至少得到我的“测试”异常。为什么它不触发?

    0 回复  |  直到 2 年前
        1
  •  0
  •   Loïc Pennamen    2 年前

    解决办法在别处。我试图在测试中更新的字段与关系实体有关。。。这个 Simulation 实体本身未更新,因此未触发侦听器。

    遗憾的是,我最终使用了一种不那么优雅的方法:使用服务“手动”调用 consolidate 方法,无论何时需要-保存时。

    推荐文章