如何在Doctrine 2 prePersist方法中坚持新的实体?

时间:2011-10-20 15:55:27

标签: callback annotations persistence doctrine-orm

我有一个使用@HasLifecycleCallbacks的实体来定义prePersist和preUpdate方法。

我的PrePersist方法是

/**
 * @ORM\OneToMany(targetEntity="Field", mappedBy="service", cascade={"persist"}, orphanRemoval=true)
 */
protected $fields;

/**
 * @PrePersist()
 */
public function populate() {
    $fieldsCollection = new \Doctrine\Common\Collections\ArrayCollection();

    $fields = array();
    preg_match_all('/%[a-z]+%/', $this->getPattern(), $fields);
    if (isset($fields[0])) {
        foreach ($fields[0] as $field_name) {
            $field = new Field();
            $field->setField($field_name);
            $field->setService($this);
            $fieldsCollection->add($field);
        }
        $this->setFields($fieldsCollection);
    }
}

我希望这可以坚持我的Field实体,但我的桌子是空的。 我应该使用EntityManager吗?如何在我的实体中检索它?

1 个答案:

答案 0 :(得分:1)

您需要使用LifecycleEventArgs来获取EntityManager并能够将实体持久保存在prePersist方法中。您可以这样检索它:

<?php
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;

class MyEventListener
{
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        // perhaps you only want to act on some "Product" entity
        if ($entity instanceof Product) 
        {
            // do something with the Product
        }
    }
}