如何在原则2 prePersist方法中持久化新实体


How persist new Entity in Doctrine 2 prePersist method?

我有一个实体与@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吗?我如何在我的实体中检索它?

你需要使用LifecycleEventArgs来获取EntityManager,并能够在prePersist方法中持久化Entity。您可以像这样检索它:

<?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
        }
    }
}