gpt4 book ai didi

symfony - 使用 NormalizerAwareTrait 的 Normalizer 空引用

转载 作者:行者123 更新时间:2023-12-05 01:44:49 25 4
gpt4 key购买 nike

我有两个 objects 具有 Parent-Child 关系。对于每个 object,我都有一个自定义的 normalizer,如下所示:

ChildNormalizer.php

use Symfony\Component\Serializer\Normalizer\scalar;

class ChildNormalizer
{
public function normalize($object, $format = null, array $context = array())
{
return [
"name" => $object->getName(),
"age" => $object->getAge(),
...
];
}

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

ParentNormalizer.php

use Symfony\Component\Serializer\Encoder\NormalizationAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\scalar;

class ParentNormalizer implements NormalizerInterface, NormalizationAwareInterface
{
use NormalizerAwareTrait;

public function normalize($object, $format = null, array $context = array())
{
return [
...
"children" => array_map(
function ($child) use ($format, $context) {
return $this->normalizer->normalize($child);
}, $object->getChildren()
),
...
];
}

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

当我尝试序列化 Parent object 进而规范化 Child object 时,我得到以下信息异常:

Call to a member function normalize() on null

我是否错过了配置步骤,或者我到底做错了什么?

最佳答案

解决了这个问题,我实现了错误的 *AwareInterface

如果 ParentNormalizer 实现了 NormalizerAwareInterface 而不是 NormalizationAwareInterface,则代码可以完美运行。

use Symfony\Component\Serializer\Encoder\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\scalar;

class ParentNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
...
}

关于symfony - 使用 NormalizerAwareTrait 的 Normalizer 空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44777531/

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