arturdoruch/simple-rest-bundle

构建RESTful API的有用函数集合

2.1.0 2021-07-20 15:51 UTC

This package is auto-updated.

Last update: 2024-09-20 22:33:12 UTC


README

一个用于构建RESTful API的有用函数集合的Symfony包。

安装

composer require arturdoruch/simple-rest-bundle

在您的应用程序的Kernel类中注册此包。

在Symfony 3中

// app/AppKernel.php
public function registerBundles()
{
    $bundles = [
        new ArturDoruch\SimpleRestBundle\ArturDoruchSimpleRestBundle(),
    ];

在Symfony >= 4中

// config/bundles.php
return [
    // Other bundles
    ArturDoruch\SimpleRestBundle\ArturDoruchSimpleRestBundle::class => ['all' => true],
];

建议

  • 为了序列化和规范化HTTP响应数据,请安装jms/serializer-bundle包。
  • 为了翻译API错误消息,请安装symfony/translation包。

配置

包配置。可用选项

artur_doruch_simple_rest:
    # Required. API endpoint paths as regexp. 
    api_paths:
        # Example:
        - ^\/product(\/.+)*$
    # Whether to flatten form error messages multidimensional array into simple array
    # with key (form names path) value (messages concatenated with ";") pairs.        
    form_error_flatten_messages: true   

用法

控制器

在您的控制器中导入ArturDoruch\SimpleRestBundle\RestTrait特性,以访问常见的REST功能。

API请求处理的示例。

<?php

namespace AppBundle\Controller;

use ArturDoruch\SimpleRestBundle\RestTrait;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

class ProductController extends Controller
{
    use RestTrait; 
    
    /**
     * Adds a new product.
     *
     * @Route(
     *     "/products",
     *     methods={"POST"},
     *     defaults={"_format": "json"}
     * )
     */
    public function post(Request $request)
    {
        // Create the form.
        $form = $this->createForm(FormType::class);
        
        // Process request with the form.
        $this->handleRequest($request, $form, true);

        // Get request data.
        $object = $form->getData();       

        // Make actions with the object. E.g. save into database.

        // Convert object into an array.
        $data = $this->normalize($object);        
               
        // Create and return the response.
        // If the "Content-Type" header is not specified then will be set to "application/json".     
        return $this->createResponse($data, 201, [
            'Location' => $this->generateUrl('app_product_get', ['id' => $object->getId()])
        ]);
    } 
}    

请求错误事件

事件名称定义在ArturDoruch\SimpleRestBundle\Http\RequestErrorEvents类中。可用事件

  1. 名称 artur_doruch_simple_rest.request_error.pre_create_response
    类常量 RequestErrorEvents::PRE_CREATE_RESPONSE
    传递给监听器方法的事件类 ArturDoruch\SimpleRestBundle\Event\RequestErrorEvent

    在请求API端点并发生异常之前创建HTTP响应之前分发此事件。 允许修改异常。

  2. 名称 artur_doruch_simple_rest.request_error.post_create_response
    类常量 RequestErrorEvents::POST_CREATE_RESPONSE
    传递给监听器方法的事件类 ArturDoruch\SimpleRestBundle\Event\RequestErrorEvent

    在请求API端点并发生异常之后创建HTTP响应时分发此事件。 提供对HTTP响应的访问。

注册事件监听器

示例

request_error_listener:
    class: RequestErrorListener
    tags:
        - { name: kernel.event_listener, event: artur_doruch_simple_rest.request_error.pre_create_response, method: onError }

有关详细信息,请参阅Symfony的事件和事件监听器文档。

端点响应

要创建端点响应,请使用ArturDoruch\SimpleRestBundle\RestTrait::createResponse()方法。默认情况下,响应设置了Content-Type: application/json头。

端点请求错误

端点请求错误的响应体包含

  • 内容类型: application/json
  • 内容体参数
    • status (字符串) HTTP状态码。
    • type (字符串) 错误类型。
    • message (字符串) 错误消息。
    • details (数组) 错误详情。