gpt4 book ai didi

php - Symfony 2 一个实体事件监听器在每个实体负载上运行

转载 作者:可可西里 更新时间:2023-10-31 22:42:15 25 4
gpt4 key购买 nike

我是 Symfony 的新手,正在关注 the Jobeet tutorial .我有三个实体——工作、类别和用户。我有以下服务监听器。

src/Ibw/JobeetBundle/Resources/config/services.yml

services:
ibw.jobeet.entity.job.container_aware:
class: Ibw\JobeetBundle\Doctrine\Event\Listener\JobListener
calls:
- [setContainer, ["@service_container"]]
tags:
- { name: doctrine.event_listener, event: postLoad }

src/Ibw/JobeetBundle/Doctrine/Event/Listener/JobListener.php

<?php
namespace Ibw\JobeetBundle\Doctrine\Event\Listener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;

class JobListener
{
/** @var ContainerInterface */
protected $container;

/**
* @param ContainerInterface @container
*/
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}

/**
* @ORM\PostLoad
*/
public function postLoad(LifecycleEventArgs $eventArgs)
{
$entity = $eventArgs->getEntity();
if (method_exists($entity, 'setContainer')) {
$entity->setContainer($this->container);
}
}
}

我原以为 postLoad 只会为 Job 实体调用,但我发现它也会为其他两个实体 Category 调用和用户。我只在 Job 实体中定义了 setContainer。所以,我得到了其他实体的未定义方法。我的解决方法是检查 method_exists

有什么方法可以只在特定实体上运行 postLoad 吗?

最佳答案

更新的答案

您的示例是一个事件监听器,但根据您的描述,您需要一个 entity listener所以结帐示例如下。

  • An Entity Listener could be any class, by default it should be a class with a no-arg constructor.
  • Different from Implementing Event Listeners an Entity Listener is invoked just to the specified entity.
  • An entity listener method receives two arguments, the entity instance and the lifecycle event.

实体

namespace Your\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\EntityListeners({"Your\WhateverBundle\EntityListener\JobListener"})
* @ORM\Table(name="job")
*/
class Job
{
// Your properties, getters and setters
}

实体监听器

namespace Your\WhateverBundle\EntityListener;

use Your\WhateverBundle\Entity\Job;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Mapping as ORM;

class JobListener
{
/** @ORM\PostLoad */
public function postLoadHandler(Job $job, LifecycleEventArgs $args)
{
// Do whatever you want
}
}

关于php - Symfony 2 一个实体事件监听器在每个实体负载上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578247/

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