Php 如何在条令2中坚持新的实体主义方法?

Php 如何在条令2中坚持新的实体主义方法?,php,doctrine-orm,callback,annotations,persistence,Php,Doctrine Orm,Callback,Annotations,Persistence,我有一个带有@HasLifecycleCallbacks的实体,用于定义prePersist和preUpdate方法 我的预科方法是 /** * @ORM\OneToMany(targetEntity="Field", mappedBy="service", cascade={"persist"}, orphanRemoval=true) */ protected $fields; /** * @PrePersist() */ public function populate() {

我有一个带有@HasLifecycleCallbacks的实体,用于定义prePersist和preUpdate方法

我的预科方法是

/**
 * @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);
    }
}
我希望这可以持久化我的字段实体,但我的表是空的。
我应该使用EntityManager吗?如何在实体中检索它?

您需要使用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
        }
    }
}