Finding out what changed via postUpdate listener in Symfony 2.1

后端 未结 4 1885
萌比男神i
萌比男神i 2021-02-20 18:14

I have a postUpdate listener and I\'d like to know what the values were prior to the update and what the values for the DB entry were after the update. Is there a way to do this

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 18:57

    Your Entitiy:

    /**
     * Order
     *
     * @ORM\Table(name="order")
     * @ORM\Entity()
     * @ORM\EntityListeners(
     *     {"\EventListeners\OrderListener"}
     * )
     */
    class Order
    {
    ...
    

    Your listener:

    class OrderListener
    {
        protected $needsFlush = false;
        protected $fields = false;
    
        public function preUpdate($entity, LifecycleEventArgs $eventArgs)
        {
            if (!$this->isCorrectObject($entity)) {
                return null;
            }
    
            return $this->setFields($entity, $eventArgs);
        }
    
    
        public function postUpdate($entity, LifecycleEventArgs $eventArgs)
        {
            if (!$this->isCorrectObject($entity)) {
                return null;
            }
    
            foreach ($this->fields as $field => $detail) {
                echo $field. ' was  ' . $detail[0]
                           . ' and is now ' . $detail[1];
    
                //this is where you would save something
            }
    
            $eventArgs->getEntityManager()->flush();
    
            return true;
        }
    
        public function setFields($entity, LifecycleEventArgs $eventArgs)
        {
            $this->fields = array_diff_key(
                $eventArgs->getEntityChangeSet(),
                [ 'modified'=>0 ]
            );
    
            return true;
        }
    
        public function isCorrectObject($entity)
        {
            return $entity instanceof Order;
        }
    }
    

提交回复
热议问题