使用 NormalizerAwareTrait 的标准化器空引用

问题描述 投票:0回答:1

我有两个

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
时,我得到以下异常:

在 null 上调用成员函数 normalize() 

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

php symfony serialization symfony-3.2
1个回答
7
投票

解决了问题,我实施了错误的

*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
{
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.