restful-template/response-template

REST API 的响应接口构建器

1.0.2 2024-06-02 01:04 UTC

This package is auto-updated.

Last update: 2024-10-02 02:11:22 UTC


README

REST API 的响应接口构建器。

目录

安装

有几种安装方式。您可以选择最适合您的方式。

Composer(推荐)

这种方式需要 Composer

$ composer require restful-template/response-template

Git

将仓库克隆到您的项目中

$ git clone https://github.com/enriquerene/response-template.git

ZIP

下载包并将其解压缩到您的项目中:[下载 ZIP](https://github.com/enriquerene/response-template/archive/main.zip)

使用方法

ResponseTemplate 需要一个有效的 HTTP 状态码。请参阅 RFC 2616 的第 10 节

简单案例

最简单的案例是实例化带有 HTTP 状态码 "200 Ok" 的 ResponseTemplate 类并调用 build 方法。

<?php
use RESTfulTemplate\ResponseTemplate;

$rest = new ResponseTemplate( 200 );
$response = $rest->build();
// $response contains following array:
// [
// 	"status" => [
// 		"code" => 200,
// 		"message" => "Ok."
// 	],
// 	"data" => null,
// 	"links" => [
// 		"self" => [
//			"url" => "https://example.com/",
//			"method" => "GET"
//		]
// 	]
// ];

响应中的数据

在构建时可以插入数据到响应中。

<?php
use RESTfulTemplate\ResponseTemplate;

$product = [
	"id" => 1,
	"name" => "product-name",
	"displayName" => "Product Name",
	"price" => "14.50",
	"stock" => 20
];

$rest = new ResponseTemplate( 200 );
$response = $rest->build( $product );
// $response contains following array:
// [
// 	"status" => [
// 		"code" => 200,
// 		"message" => "Ok."
// 	],
// 	"data" => [
//		"id" => 1,
// 		"name" => "product-name",
// 		"displayName" => "Product Name",
// 		"price" => "14.50",
// 		"stock" => 20
// 	],
// 	"links" => [
// 		"self" => [
//			"url" => "https://example.com/products/1",
//			"method" => "GET"
//		]
// 	]
// ];

链接设置

您可以使用 setLink 方法设置一个链接到响应。

<?php
use RESTfulTemplate\ResponseTemplate;

$products = [
	[
		"id" => 1,
		"name" => "product-name",
		"displayName" => "Product Name",
		"price" => "14.50",
		"stock" => 20
	],
	/* ...more ones */
];

$rest = new ResponseTemplate( 200 );
$rest = $rest->setLink( "next", "https://example.com/products?page=2" );
$response = $rest->build( $products );
// $response contains following array:
// [
// 	"status" => [
// 		"code" => 200,
// 		"message" => "Ok."
// 	],
// 	"data" => [
//		[
//			"id" => 1,
//			"name" => "product-name",
//			"displayName" => "Product Name",
//			"price" => "14.50",
//			"stock" => 20
//		],
// 		/* ...more ones */
//	],
// 	"links" => [
// 		"self" => [
//			"url" => "https://example.com/products",
//			"method" => "GET"
//		],
// 		"next" => [
//			"url" => "https://example.com/products?page=2",
//			"method" => "GET"
//		]
// 	]
// ];

您可以在 setLink 方法中插入第三个参数来定义链接的 "method" 属性。例如,如果您想与 POST 路由一起工作,您可能希望使用 $rest = $rest->setLink( "create", "/products", "POST" );

计划

本项目旨在保持与标准的一致性。未来的版本可能与 RFC 7231 保持一致。路线图中的某些实现

设置自定义链接键

  • 如果只给出了以 ? 开头的查询字符串,将检索与 self url 中的相同基本名称和路径。
  • 如果只给出了路径,将检索与 self url 中的相同基本名称。
  • 如果给出了包含 . 的基本名称,将检索与 self url 中的相同协议。
  • 包含 http/https 协议的完整路径将原样放入自定义键 URL 属性中。

支持

如果您需要帮助,可以提出一个问题。

贡献

提交一个 pull request 或向支持发送电子邮件。