phl/laravel-respond-to

为Laravel提供类似Rails的respond_to功能

2.1.0 2021-12-11 23:31 UTC

This package is auto-updated.

Last update: 2024-09-12 05:43:50 UTC


README

PHP Tests

这个库将为您提供类似Rails的respond_to功能。此功能允许控制器动作根据请求Accept头(格式)返回不同的响应。

安装

composer require phl/laravel-respond-to

用法

您可以通过使用PHL\LaravelRespondTo\Respond类在任何控制器动作中使用respond to功能。

<?php

use PHL\LaravelRespondTo\Respond;

class MyController
{
    public function index()
    {
        return Respond::to('html')->withView('hello', ['name' => 'John Doe'])
            ->to('json')->with(['key' => 'value'])
            ->to('txt')->with('some text')
            ->to('xml')->with(function () {})
            ->to('rss')->with(new \Illuminate\Http\Response())
            ->to('css')->with(new ResponsableClass);
    }
}

现在,这个控制器可以以不同的响应响应不同的格式。

每次对to函数的调用后必须跟一个withwithView调用。

默认格式

如果当前请求要求返回不支持格式的响应,则将返回默认格式。

默认格式是html,您可以使用default函数更改它。

use PHL\LaravelRespondTo\Respond;

Respond::withNewRespond()
    ->to('json')->with(['key' => 'value'])
    ->default('json');

如果没有为默认格式设置任何响应,则在控制器尝试解析响应时将抛出异常。

支持格式

在内部,此库依赖于Symfony请求MIME类型列表。此列表最初设置以下格式

$formats = [
    'html' => ['text/html', 'application/xhtml+xml'],
    'txt' => ['text/plain'],
    'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'],
    'css' => ['text/css'],
    'json' => ['application/json', 'application/x-json'],
    'jsonld' => ['application/ld+json'],
    'xml' => ['text/xml', 'application/xml', 'application/x-xml'],
    'rdf' => ['application/rdf+xml'],
    'atom' => ['application/atom+xml'],
    'rss' => ['application/rss+xml'],
    'form' => ['application/x-www-form-urlencoded'],
];

您可以通过以下方式向此列表添加新格式

request()->setFormat('csv', 'text/csv');

在新的行上写入第一个to

如果您像我一样,更喜欢将to函数的每次调用都放在自己的行上,我通过withNewRespond函数添加了一些语法糖。

use PHL\LaravelRespondTo\Respond;

Respond::withNewRespond()
    ->to('html')->with('some html')
    ->to('json')->with(['key' => 'value'])
    ->to('xml')->withView('welcome_xml');

贡献和帮助

如果您对此库的用法有任何疑问,请随时提出问题:)

如果您认为文档或代码可以改进,请提出PR,我会很乐意审阅它!