使用NormalizerAwareTrait的Normalizer null引用

时间:2017-06-27 10:06:06

标签: symfony serialization 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);
    }
}

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会使docker restart container-name sudo service postgresql restart 正常化,我会得到以下异常:

Call to a member function normalize() on null

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

1 个答案:

答案 0 :(得分:4)

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