首先我会检查你的setName函数实际上正在做某事($this-> name = $name...)如果它已经在工作,那么你可以在你的 services.yml 上定义一个事件监听器,当你叫同花顺。
entity.listener:
class: YourName\YourBundle\EventListener\EntityListener
calls:
- [setContainer, ["@service_container"]]
tags:
- { name: doctrine.event_listener, event: onFlush }
然后定义 EntityListener
namespace YourName\YourBundle\EventListener;
use Doctrine\ORM\Event;
use Symfony\Component\DependencyInjection\ContainerAware;
class EntityListener extends ContainerAware
{
/**
* Gets all the entities to flush
*
* @param Event\OnFlushEventArgs $eventArgs Event args
*/
public function onFlush(Event\OnFlushEventArgs $eventArgs)
{
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
//Insertions
foreach ($uow->getScheduledEntityInsertions() as $entity) {
# your code here for the inserted entities
}
//Updates
foreach ($uow->getScheduledEntityUpdates() as $entity) {
# your code here for the updated entities
}
//Deletions
foreach ($uow->getScheduledEntityDeletions() as $entity) {
# your code here for the deleted entities
}
}
}
如果您需要知道哪些实体正在被更改,但在将它们保存到数据库后对其进行处理,只需将更改的实体存储在私有数组中,然后定义一个从数组中获取实体的 onFlush 事件。
顺便说一句,要触发此类事件,您需要在实体上添加 @ORM\HasLifecycleCallbacks。