概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:30:14 | 238 次阅读 | 评论: 0 | 来源: 网络整理

Serializing and deserializing to and from objects and different formats (e.g. JSON or XML) is a very complex topic. Symfony comes with a Serializer Component, which gives you some tools that you can leverage for your solution.

In fact, before you start, get familiar with the serializer, normalizers and encoders by reading the Serializer Component. You should also check out the JMSSerializerBundle, which expands on the functionality offered by Symfony’s core serializer.

Activating the Serializer

2.3 新版功能: The Serializer has always existed in Symfony, but prior to Symfony 2.3, you needed to build the serializer service yourself.

The serializer service is not available by default. To turn it on, activate it in your configuration:

  • YAML
    # app/config/config.yml
    framework:
        # ...
        serializer:
            enabled: true
    
  • XML
    <!-- app/config/config.xml -->
    <framework:config>
        <!-- ... -->
        <framework:serializer enabled="true" />
    </framework:config>
    
  • PHP
    // app/config/config.php
    $container->loadFromExtension('framework', array(
        // ...
        'serializer' => array(
            'enabled' => true
        ),
    ));
    

Adding Normalizers and Encoders

Once enabled, the serializer service will be available in the container and will be loaded with two encoders (JsonEncoder and XmlEncoder) but no normalizers, meaning you’ll need to load your own.

You can load normalizers and/or encoders by tagging them as serializer.normalizer and serializer.encoder. It’s also possible to set the priority of the tag in order to decide the matching order.

Here is an example on how to load the GetSetMethodNormalizer:

  • YAML
    # app/config/config.yml
    services:
       get_set_method_normalizer:
          class: SymfonyComponentSerializerNormalizerGetSetMethodNormalizer
          tags:
             - { name: serializer.normalizer }
    
  • XML
    <!-- app/config/config.xml -->
    <services>
        <service id="get_set_method_normalizer" class="SymfonyComponentSerializerNormalizerGetSetMethodNormalizer">
            <tag name="serializer.normalizer" />
        </service>
    </services>
    
  • PHP
    // app/config/config.php
    use SymfonyComponentDependencyInjectionDefinition;
    
    $definition = new Definition(
        'SymfonyComponentSerializerNormalizerGetSetMethodNormalizer'
    ));
    $definition->addTag('serializer.normalizer');
    $container->setDefinition('get_set_method_normalizer', $definition);
    
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务