如何在Symfony 4中使用datetimeNormalizer?

时间:2018-12-22 16:35:44

标签: symfony entity serializer

这是我的控制者:

use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;


public function index($slug, Request $request, SerializerInterface $serializer)
  {
    $table = $this->getDoctrine()->getRepository($EntityName)->findAll();
    $serializer = new Serializer(array(new DateTimeNormalizer('d.m.Y'), new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
    $data = $serializer->serialize($table, 'json');
    return $this->render('index.html.twig', ['data' => $data]);
  }

它运行良好,但是我得到警告:

  

不建议使用的用户:将配置选项直接传递给   自Symfony 4.2起不推荐使用构造函数,请使用默认上下文   代替。

1 个答案:

答案 0 :(得分:0)

问题在于如何构建序列化器,更具体地说是如何构建DateTimeNormalizer。只要没有提供上下文,您就可以看到error being triggered in the constructor of that class

简单的解决方法是将数组作为第一个参数传递:

do { .. } while

所以只需将new Serializer( array( new DateTimeNormalizer(array('datetime_format' => 'd.m.Y')), new GetSetMethodNormalizer() ), array( 'json' => new JsonEncoder() ) ); 替换为d.m.Y

因为无论如何都传递了SerializerInterface,所以您可能想在services.yaml中配置序列化器:

array('datetime_format' => 'd.m.Y')

然后,您可以在控制器中通过更改参数名称来注入序列化器

services:
    _defaults:
        ... # other default settings
        bind:
            Symfony\Component\Serializer\SerializerInterface $dateSerializer: '@app.date_serializer'

    Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer: ~
    Symfony\Component\Serializer\Encoder\JsonEncoder: ~

    app.date_normalizer:
        class: Symfony\Component\Serializer\Normalizer\DateTimeNormalizer
        arguments:
            - { 'datetime_format': 'd.m.Y' }

    app.date_serializer:
        class: Symfony\Component\Serializer\Serializer
        arguments:
            - ['@app.date_normalizer', '@Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer']
            - ['@Symfony\Component\Serializer\Encoder\JsonEncoder']

实际上,由于您的服务配置中有绑定,因此只要您想在哪里重复使用该序列化程序,都可以通过向其注入public function index($slug, Request $request, SerializerInterface $dateSerializer) 来获得它。

请注意,绑定仅适用于Symfony 4.2。在旧版本中,您必须删除开头的类型(SerializerInterface),因为这是一项新功能。我认为其他所有东西都应该可以在Symfony 3.4和4.0上使用。