Php 尝试向资源响应添加额外数据时出错
我正在尝试向特定资源添加一些额外数据,因此我遵循了有关的文档,但当我测试资源时,出现了以下错误: 在(…)/vendor/api platform/core/src/Serializer/AbstractItemNormalizer.php的第426行中调用null上的成员函数normalize() 我与这个错误斗争了将近两天,我不知道我是否遗漏了一些细节,或者这不是向资源添加额外数据的正确方法。 这是我的资源定义:Php 尝试向资源响应添加额外数据时出错,php,symfony,serialization,api-platform.com,Php,Symfony,Serialization,Api Platform.com,我正在尝试向特定资源添加一些额外数据,因此我遵循了有关的文档,但当我测试资源时,出现了以下错误: 在(…)/vendor/api platform/core/src/Serializer/AbstractItemNormalizer.php的第426行中调用null上的成员函数normalize() 我与这个错误斗争了将近两天,我不知道我是否遗漏了一些细节,或者这不是向资源添加额外数据的正确方法。 这是我的资源定义: AppBundle\Entity\MediaGenerator\Teaser:
AppBundle\Entity\MediaGenerator\Teaser:
attributes:
access_control: "is_granted('ROLE_ADMIN')"
normalization_context:
groups: ['teaser','teaser-read']
denormalization_context:
groups: ['teaser','teaser-write']
order:
position: 'ASC'
这是我的自定义规范化器:
class ApiNormalizer implements NormalizerInterface
{
private $normalizer;
public function __construct(NormalizerInterface $normalizer)
{
$this->normalizer = $normalizer;
}
public function supportsNormalization($data, $format = null)
{
return $data instanceof Teaser;
}
public function normalize($object, $format = null, array $context = [])
{
$data = $this->normalizer->normalize($object, $format, $context);
if (is_array($data)) {
$data['view'] = "SOME TRANSFORMATION ON TEASER VIEW";
}
return $data;
}
public function supportsDenormalization($data, $type, $format = null)
{
return $this->normalizer->supportsNormalization($data, $type, $format);
}
public function denormalize($data, $class, $format = null, array $context = [])
{
return $this->normalizer->denormalise($data, $class, $format, $context);
}
}
这是我的服务。yml声明:
AppBundle\Serializer\ApiNormalizer:
decorates: 'api_platform.jsonld.normalizer.item'
arguments: [ '@AppBundle\Serializer\ApiNormalizer.inner' ]
autoconfigure: false
其他所有功能都很有效,config.yml中的序列化程序被启用为{enable_annotations:true}
有问题吗
提前感谢,ApiPlatform做了大量工作 首先,检查序列化程序是否已启用
注射依赖的祸害
这里您遇到的是一个缺少的注入依赖项。主要是因为您正在调用的方法没有在其他地方运行相同的代码依赖性检查。具体而言:
// $this->serializer is NULL
return $this->serializer->normalize($attributeValue, $format, $context);
你会注意到:
AbstractItemNormalizer::getAttributeValue
没有此检查(而且确实应该)
规范化程序需要调用setSerializer
对基本序列化程序的快速检查显示它被定义为:
这意味着每个序列化程序都要通过类似于依赖项反转的模式(对象本身调用父setter来设置自身)将依赖项注入到使用它的每个规范化程序中:
class Serializer {
public function __construct($normalizer) {
$normalizer->setSerializer($this);
}
这一切归结为两个要求:
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ApiNormalizer());
$serializer = new Serializer($normalizers, $encoders);
class Serializer {
public function __construct($normalizer) {
$normalizer->setSerializer($this);
}
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ApiNormalizer());
$serializer = new Serializer($normalizers, $encoders);