ptournet/laravel-multiformat

Laravel 的多格式端点

v1.1.1 2020-08-10 18:40 UTC

This package is auto-updated.

Last update: 2024-09-11 04:34:45 UTC


README

Latest Stable Version Latest Unstable Version Build Status Total Downloads License

此包允许单个 Laravel 路由以不同的格式(通常是 HTML 和 JSON)响应。它旨在作为未维护的包:m1guelpf/laravel-multiformat 的直接替换,并包含新功能和与最新 Laravel 版本的兼容性。

安装

您可以通过 composer 安装此包

composer require ptournet/laravel-multiformat

用法

<?php

/**
 * Mark a route as 'multiformat' to allow different extensions (html, json, xml, etc.)
 *
 * This route will match all of these requests:
 *     /podcasts/4
 *     /podcasts/4.json
 *     /podcasts/4.html
 *     /podcasts/4.zip
 */
Route::get('/podcasts/{id}', 'PodcastsController@show')->multiformat();

/**
 * Use `Request::matchFormat()` to return the right response for the requested format.
 *
 * Supports closures to avoid doing unnecessary work, and returns 404 if the
 * requested format is not supported.
 *
 * Will also take into account the `Accept` header if no extension is provided.
 */
class PodcastsController
{
    public function show($id)
    {
        $podcast = Podcast::findOrFail($id);
        
        return request()->matchFormat([
            'html' => view('podcasts.show', [
                'podcast' => $podcast,
                'episodes' => $podcast->recentEpisodes(5),
            ]),
            'json' => $podcast,
            'xml' => function () use ($podcast) {
                return response($podcast->toXml(), 200, ['Content-Type' => 'text/xml']);
            }
        ]);
    }
}

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

贡献

有关详细信息,请参阅 CONTRIBUTING

安全

如果您发现任何与安全相关的问题,请通过电子邮件 ptournet (at sign) gmail.com 而不是使用问题跟踪器。

鸣谢

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件