如何修复Symfony中的“已有数据”错误

时间:2019-08-12 13:13:14

标签: php symfony jms

我希望在序列化后添加交货日期

所以我用方法“ onPostSerialize”创建了一个事件监听器。

这是我的听众:

namespace App\ApiBundle\Serializer\Listener;

use JMS\Serializer\EventDispatcher\Events;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;

class BrandListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            [
                'event' => Events::POST_SERIALIZE,
                'format' => 'json',
                'class' => 'App\ApiBundle\Entity\Brand',
                'method' => 'onPostSerialize',
            ]
        ];
    }

    public static function onPostSerialize(ObjectEvent $event)
    {
        $object = $event->getObject();

        $date = new \Datetime();
        $event->getVisitor()->addData('delivered_at', $date->format('l jS \of F Y h:i:s A'));
    }
}

即使在清空缓存时,我也遇到一个错误,告诉我数据具有相同的名称(除了否)...

出现错误Symfony:

  

InvalidArgumentException已经有“ delivered_at”的数据

2 个答案:

答案 0 :(得分:0)

在app / config / services.yml中,将自动配置的值更改为 false

答案 1 :(得分:0)

 public function onPostSerialize(ObjectEvent $event): void
 {
    $propertyName = 'deliveredAt';
    $value        =  (new \DateTime())->format('l jS \of F Y h:i:s A');
    $className    = Brand::class;

    /** @var JsonSerializationVisitor $visitor */
    $visitor  = $event->getVisitor();
    $metadata = new VirtualPropertyMetadata($className, $propertyName);
    
    // check if property is displayed
    if ($visitor->hasData($metadata->name)) {
        $visitor->visitProperty(
            new StaticPropertyMetadata($className, $metadata->name, $value),
            $value
        );
    }
}

但是您也可以使用另一种方式:在 Brand 实体中添加Virtual Property

/**
 * @JMS\VirtualProperty({name: "delivered_at"})
 */
public function getDeliveredAt()
{
    return (new \DateTime())->format('l jS \of F Y h:i:s A');
}