gpt4 book ai didi

Symfony3 - 序列化嵌套实体

转载 作者:行者123 更新时间:2023-12-01 19:35:56 25 4
gpt4 key购买 nike

所以我有几个 Doctrine 实体,一个订阅和一个订阅者。单个订阅者有很多订阅(manyToOne)。我为这两个实体都编写了自定义规范化器,但在将订阅者规范化为 JSON 后,我无法让订阅者显示在订阅中。

我能够让它工作的唯一方法是将“订阅者”规范器传递给“订阅”规范器。似乎我应该能够使用 SerializerAwareNormalizer Trait 或类似的东西让 Symfony 递归规范化我的相关实体。

services:
acme.marketing.api.normalizer.subscription:
class: acme\MarketingBundle\Normalizer\SubscriptionNormalizer
arguments: ['@acme.marketing.api.normalizer.subscriber']
public: false
tags:
- { name: serializer.normalizer }
acme.marketing.api.normalizer.subscriber:
class: acme\MarketingBundle\Normalizer\SubscriberNormalizer
public: false
tags:
- { name: serializer.normalizer }

和归一化器...

<?php
namespace acme\MarketingBundle\Normalizer;

use acme\MarketingBundle\Entity\Subscription;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class SubscriptionNormalizer implements NormalizerInterface
{


private $subscriberNormalizer;

public function __construct($subscriberNormalizer)
{
$this->subscriberNormalizer = $subscriberNormalizer;
}

public function normalize($subscription, $format = null, array $context = [])
{

/* @var $subscription Subscription */
$subscriber = $subscription->getSubscriber();

return [
"id" => $subscription->getId(),
"subscriber" => $this->subscriberNormalizer->normalize($subscriber, $format)
];
}



public function supportsNormalization($data, $format = null)
{
return $data instanceof Subscription;
}

}

有没有更好的方法来完成这个?

最佳答案

google 了几个小时也没搞明白。在 SO 上发布,5 分钟后点击正确的谷歌链接:(。答案似乎是在自定义规范化器上实现 NormalizerAwareInterface,然后使用 NormalizerAwareTrait 访问嵌套实体的规范化器。

<?php
namespace acme\MarketingBundle\Normalizer;

use acme\MarketingBundle\Entity\Subscription;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class SubscriptionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{

use NormalizerAwareTrait;

public function normalize($subscription, $format = null, array $context = [])
{

return [
"id" => $subscription->getId(),
"subscriber" => $this->normalizer->normalize($subscription->getSubscriber())
];
}



public function supportsNormalization($data, $format = null)
{
return $data instanceof Subscription;
}

}

关于Symfony3 - 序列化嵌套实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com