How to access old values on PrePersist LifecycleCallback in Doctrine2

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-01 04:23:06

问题


I have an entity in Doctrine2 and use the HasLivecycleCallbacks with PrePersist. In general this works fine, but I would like to change the version only, when certain fields in my entity change. Do I have a chance to get the old Values? Or just the keys that have been changed?

/**
 * @ORM\HasLifecycleCallbacks
 */
class Person {


    /**
     * @PrePersist
     * @PreUpdate
     */
    public function increaseVersion() {


            if ( $this->version == null ) {
                $this->version = 0;
            }
            // only do this, when a certain attribute changed
            $this->version++;
    }
}

回答1:


It depends on which LifecycleEvent we are talking about. PrePersist and PreUpdate are different events.

PreUpdate is fired before an Entity is, well, updated. This will give you a PreUpdateEventArgs object, which is an extended LifecycleEventArgs object. This will allow you to query for changed fields and give you access to the old and new value:

if ($event->hasChangedField('foo')) {
    $oldValue = $event->getOldValue('foo');
    $newValue = $event->getNewValue('foo');
}

You could also get all the changed field values through getEntityChangeSet(), which would give you an array like this:

array(
    'foo' => array(
        0 => 'oldValue',
        1 => 'newValue'
    ),
    // more changed fields (if any) …
)

PrePersist, on the other hand, assumes a fresh Entity (think insert new row). In PrePersist, you'll get a LifecycleEventArgs object which only has access to the Entity and the EntityManager. In theory, you can get access to the UnitOfWork (which keeps track of all the changes to Entities) through the EntityManager, so you could try to do

$changeSet = $event->getEntityManager()->getUnitOfWork()->getEntityChangeSet(
    $event->getEntity()
);

to get the changes for the to be persisted Entity. You could then check this array for changed fields. However, since we are talking about an insert and not an update, I assume all fields wil be considered "changed" and the old values will likely be all null. I am not sure, this will work as you need it.

Further reference: http://docs.doctrine-project.org/en/2.0.x/reference/events.html



来源:https://stackoverflow.com/questions/18762695/how-to-access-old-values-on-prepersist-lifecyclecallback-in-doctrine2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!