使用 NormalizerAwareTrait 的 Normalizer null 引用

Unf*_*lux 2 serialization symfony symfony-3.2

我有两个objectsParent-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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试序列化Parent object这反过来规范化Child object我得到以下异常:

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

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

Unf*_*lux 5

解决了这个问题,我正在实施错误的*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
{
    ...
}
Run Code Online (Sandbox Code Playgroud)