voryx/restgeneratorbundle

Symfony 2 的 REST API 生成器

安装数: 128,721

依赖者: 1

建议者: 0

安全性: 0

星标: 176

关注者: 29

分支: 70

开放性问题: 16

类型:symfony-bundle

0.4.0 2016-04-18 12:29 UTC

This package is auto-updated.

Last update: 2024-09-19 09:21:41 UTC


README

SensioLabsInsight

关于

CRUD 类型的 REST 生成器

功能

  • 从实体生成 RESTful 动作
  • 简化设置 RESTful 控制器的过程

安装

在您的 composer.json 中要求 "voryx/restgeneratorbundle" 包并更新您的依赖。

$ php composer.phar require voryx/restgeneratorbundle dev-master

将 VoryxRestGeneratorBundle 添加到您应用程序的内核中,以及其他依赖项

public function registerBundles()
{
    $bundles = array(
        //...
          new Voryx\RESTGeneratorBundle\VoryxRESTGeneratorBundle(),
          new FOS\RestBundle\FOSRestBundle(),
          new JMS\SerializerBundle\JMSSerializerBundle($this),
          new Nelmio\CorsBundle\NelmioCorsBundle(),
        //...
    );
    //...
}

配置

此包依赖于许多其他 Symfony 包,因此它们需要配置才能使生成器正常工作

framework:
    csrf_protection: false #only use for public API

fos_rest:
    routing_loader:
        default_format: json
    param_fetcher_listener: true
    body_listener: true
    #disable_csrf_role: ROLE_USER
    body_converter:
        enabled: true
    view:
        view_response_listener: force

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

sensio_framework_extra:
    request: { converters: true }
    view:    { annotations: false }
    router:  { annotations: true }

生成控制器

生成 REST 控制器

$ php app/console voryx:generate:rest

这将引导您通过生成器,该生成器将为实体生成一个 RESTful 控制器。

示例

创建一个名为 'Post' 的新实体

$ php app/console doctrine:generate:entity --entity=AppBundle:Post --format=annotation --fields="name:string(255) description:string(255)" --no-interaction

更新数据库模式

$ php app/console doctrine:schema:update --force

生成 API 控制器

$ php app/console voryx:generate:rest --entity="AppBundle:Post"

使用 API

如果您选择了默认选项,您将能够像这样开始使用 API

创建新的帖子 (POST)

$ curl -i -H "Content-Type: application/json" -X POST -d '{"name" : "Test Post", "description" : "This is a test post"}' http://localhost/app_dev.php/api/posts

更新 (PUT)

$ curl -i -H "Content-Type: application/json" -X PUT -d '{"name" : "Test Post 1", "description" : "This is an updated test post"}' http://localhost/app_dev.php/api/posts/1

获取所有帖子 (GET)

$ curl http://localhost/app_dev.php/api/posts

获取一个帖子 (GET)

$ curl http://localhost/app_dev.php/api/posts/1

删除 (DELETE)

$ curl -X DELETE  http://localhost/app_dev.php/api/posts/1

相关实体

如果您希望表单能够在 POST、PUT 或 PATCH 中将相关实体转换为正确的实体 ID,请使用 voryx_entity 表单类型

#Form/PostType()

    ->add(
        'user', 'voryx_entity', array(
            'class' => 'Acme\Bundle\Entity\User'
        )
    )