kduma/content-negotiable-responses

Laravel 用于创建内容类型可协商响应的辅助函数

1.0 2022-10-20 12:58 UTC

This package is auto-updated.

Last update: 2024-08-29 18:24:28 UTC


README

composer require kduma/content-negotiable-responses

内容格式(适用于 ArrayResponseBasicViewResponse

当前支持的格式有

  • text/plain(默认禁用,要在自定义类中启用它,请实现 TextResponseInterface)- 结果响应将是内置 PHP 函数 print_r 的输出
  • application/json - 结果响应将是内置 PHP 函数 json_encode 的输出
  • application/yaml - 结果响应将使用 symfony/yaml 包生成
  • application/xml - 结果响应将使用 spatie/array-to-xml 包生成
  • application/msgpack - 结果响应将使用 rybakit/msgpack 包生成
  • text/html(仅适用于 BasicViewResponse)- 结果响应将使用构造函数中提供的带有传递数据数组的视图生成

用法

基本数组用法(用于 API 响应)

Route::get('/test', function () {
    return new \KDuma\ContentNegotiableResponses\ArrayResponse([
        'success' => true,
        'timestamp' => time(),
    ]);
});

因此,响应将根据 Accept HTTP 头中传递的可接受格式进行格式化,如果没有指定,则为 JSON。

基本视图用法(用于 Web 和 API 响应)

Route::get('/', function () {
    return new \KDuma\ContentNegotiableResponses\BasicViewResponse('welcome', [
        'success' => true,
        'timestamp' => time(),
    ]);
});

自定义用法

namespace App\Http\Responses;

use KDuma\ContentNegotiableResponses\BaseViewResponse;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class UsersListResponse extends BaseViewResponse
{
    public $users;

    public function __construct(Collection $users)
    {
        $this->users = $users;
    }

    protected function generateView(Request $request)
    {
        return $this->view('users.list');
    }
}

Route::get('/users', function () {
    return new \App\Http\Responses\UsersListResponse(\App\User::all());
});

因此,当在浏览器中打开时,将渲染带有传递的所有公共属性的 users.list 视图。在非 HTML 客户端(指定其他 Accept 头)将获得序列化的公共属性(在任何支持的格式中),例如

{
    "users": [
        {
            "name": "user 1",
            "email": "user1@localhost"
        },
        {
            "name": "user 2",
            "email": "user2@localhost"
        },
        {
            "name": "user 3",
            "email": "user3@localhost"
        }
    ]
}

如果您想自定义序列化数组,则需要重写 getDataArray 方法

/**
 * @return array
 */
protected function getDataArray() {
	return [
		'my_super_users_collection' => $this->users->toArray(),
		'hello' => true
	];
}

然后结果将是

{
    "my_super_users_collection": [
        {
            "name": "user 1",
            "email": "user1@localhost"
        },
        {
            "name": "user 2",
            "email": "user2@localhost"
        },
        {
            "name": "user 3",
            "email": "user3@localhost"
        }
    ],
    "hello": true
}