matmar10/rest-api-bundle

一个允许使用 @Api 注解来自动将任何控制器的返回值序列化为 JMS Serializer 的 Symfony Bundle。

安装: 18

依赖者: 0

建议者: 0

安全: 0

星标: 2

关注者: 2

分支: 1

开放问题: 3

类型:symfony-bundle

1.0.0-rc3 2014-07-25 00:23 UTC

README

一个允许使用 @Api 注解来自动将任何控制器的返回值序列化为 JMS Serializer 的 Symfony Bundle。

此 Bundle 使用流行的 (JMS Serializer Bundle)[https://github.com/schmittjoh/JMSSerializerBundle] 进行所有序列化。

JMS 序列化注解实体将相应地进行序列化。

安装

将 Bundle 添加到您的 Symfony 项目的 composer 文件中

   "require": {
       "matmar10/rest-api-bundle": "~0.3.2"
   },
   ...

将 Bundle 添加到 Kernel 并运行 composer update

    // in app/AppKernel.php
    public function registerBundles()
    {
        $bundles = array(
            ...
            new Matmar10\Bundle\RestApiBundle\Matmar10RestApiBundle(),
        );

    }

注解控制器方法;返回值将自动序列化为 JSON 或 XML

<?php

    namespace Acme\DemoBundle\Controller;

    use Matmar10\Bundle\RestApiBundle\Annotation\Api;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;

    /**
     * @Api("json")
     */
    class RestApiBundleTestJsonController extends Controller
    {
        public function getArrayAsJsonAction()
        {
            return array(1,2,3,4);
        }

        /**
         * @Api("xml")
         */
        public function getArrayAsXmlAction()
        {
            return array(1,2,3,4);
        }
    }
}

选项

使用 @Api 注解来指示控制器或方法的返回结果应序列化为 JSON 或 XML 响应(或任何其他由您的 JMS Serializer Bundle 接受的配置序列化类型)。

@Api 注解的值表示序列化类型

    @Api("json")
    public function getPersonAction()
    {
        $person = new Person();
        $person->setName("Matthew J. Martin");
        $person->setAge(28);
        return $person;
    }

// results in: {"name":"Matthew J. Martin","age":28}

您还可以指定不同的默认状态码(例如,当创建实体时)

    @Api("json", responseCode=201)
    public function createPersonAction()
    {
        $person = new Person();
        // process the request, persist the entity, and then return it
        return $person;
    }

异常

异常将自动序列化为所需的序列化格式。