我正在根据Normalizer
文档页面https://symfony.com/doc/current/serializer/custom_normalizer.html上的教程创建自己的Symfony
,我发现它不完整,因为它告诉您如何创建但不应用它,这是第一点。
然后根据我在Symfony
中的一点经验,我试图猜测如何将数据传递到normalizer
进行正确的计算,我尝试传递的数据不是{{ 1}},可以是services
,但这些数据都不允许我使用,真的需要了解,还是需要重构才能获得所需的内容?
我输入了String or a Request object
代码以很好地了解我要寻找的内容。
规范化器:
normalizer
应用规范化器: 传递来自对象Request的动态变量$ rangeDate。
<?php
namespace App\Serializer;
use App\Entity\Task;
use App\Traits\TaskControl;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class TaskNormalizer implements NormalizerInterface
{
use TaskControl;
private $normalizer;
private $rangeDate;
public function __construct(ObjectNormalizer $normalizer, $rangeDate )
{
$this->normalizer = $normalizer;
$this->rangeDate = $rangeDate;
}
public function normalize($task, $format = null, array $context = [])
{
$data = $this->normalizer->normalize($task, $format, $context);
dd($this->rangeDate);
$data['totalWork'] = $this->timeTask($task,$this->rangeDate);
return $data;
}
public function supportsNormalization($task, $format = null, array $context = []): bool
{
return $task instanceof Task;
}
}
这是我得到的错误:
$rangeDate = $request->request->get('range','all');
$serializer = new Serializer([new TaskNormalizer($normalizer,$rangeDate)]);
$data = $serializer->normalize($attendances, null, ['attributes' => $attributes]);
答案 0 :(得分:2)
为什么要将范围日期作为构造函数参数传递?
Normalizer是服务依赖项,rangeDate是动态值。
您可以将其作为方法规范化的参数传递,而不是作为新参数或在上下文数组中传递:
$rangeDate = $request->request->get('range','all');
$serializer = new Serializer([new TaskNormalizer($normalizer)]);
$data = $serializer->normalize($attendances, null, ['attributes' => $attributes, 'rangeDate' => $rangeDate]);
答案 1 :(得分:0)
您将没有明确声明您的服务...类似这样的事情应该可以解决:
## services.yml
App\Serializer\TaskNormalizer :
arguments:
$normalizer: '@serializer.normalizer.object' ## check the alias ...
$rangeDate: '%range_date%'
请记住,出于依赖关系反转的原则,它比类更好地依赖于接口。因此,您应该考虑将构造函数更改为:
## your class
public function __construct(NormalizerInterface $normalizer, $rangeDate )
{
$this->normalizer = $normalizer;
$this->rangeDate = $rangeDate;
}