我有一个包含2个属性的实体,name
和photo
。从数据库中读取name
属性,但我必须在photo
属性中填入一些其他信息。
我已按照文档中的 Writing a Custom Nomalizer 教程进行操作,并制作了自定义规范化器:
<?php
namespace App\Serializer;
use App\Entity\Style;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
final class StyleNormalizer implements NormalizerInterface, DenormalizerInterface
{
private $normalizer;
private $uploaderHelper;
public function __construct(NormalizerInterface $normalizer, UploaderHelper $uploaderHelper)
{
if (!$normalizer instanceof DenormalizerInterface) {
throw new \InvalidArgumentException('The normalizer must implement the DenormalizerInterface');
}
$this->normalizer = $normalizer;
$this->uploaderHelper = $uploaderHelper;
}
public function denormalize($data, $class, $format = null, array $context = [])
{
return $this->normalizer->denormalize($data, $class, $format, $context);
}
public function supportsDenormalization($data, $type, $format = null)
{
return $this->normalizer->supportsDenormalization($data, $type, $format);
}
public function normalize($object, $format = null, array $context = [])
{
if ($object instanceof Style) {
$object->setPhoto('http://api-platform.com');
}
return $this->normalizer->normalize($object, $format, $context);
}
public function supportsNormalization($data, $format = null)
{
return $this->normalizer->supportsNormalization($data, $format);
}
}
但photo
属性未填充所需信息。
经过一些调试后,我发现supportsNormalization
方法执行了两次(对于每个数据库元素)。如果我打印$data
变量,我第一次获得实体name
属性,第二次获得photo
属性null
属性。我从来没有得到整个Style
实体。然后,supportsNormalitzation
方法始终返回false
。
如何获取完整的Style
实体并修改其属性?
谢谢!
答案 0 :(得分:0)
尝试将此添加到您的supportsNormalization
方法中:
public function supportsNormalization($data, $format = null)
{
return
$this->normalizer->supportsNormalization($data, $format)
&& is_object($data) && $data instanceof Style::class
;
}