mleczek / laravel-negotiator
Laravel API的内容协商
v1.0.1
2017-01-21 11:36 UTC
Requires
- illuminate/http: ^5.3
- illuminate/support: ^5.3
- mleczek/xml: ^1.2
Requires (Dev)
- illuminate/database: ^5.3
- mockery/mockery: ~0.9
- phpunit/phpunit: ~5.7
This package is auto-updated.
Last update: 2024-09-05 03:51:16 UTC
README
安装
使用Composer安装此包
composer require mleczek/laravel-negotiator
在 config/app.php
中添加 NegotiatorServiceProvider
'providers' => [ Mleczek\Negotiator\NegotiatorServiceProvider::class, ]
使用
包为 ResponseFactory
提供了 negotiate
宏
public function show(User $user) { return response()->negotiate($user); }
也可以使用 Mleczek\Negotiator\ContentNegotiation
类达到相同的效果
public function __construct(ContentNegotiation $cn) { $this->cn = $cn; } public function show(Request $request, User $user) { return $cn->negotiate($request, $user); }
对于 negotiate
方法和宏,还有一个参数可以覆盖指定内容类型的返回结果
public function show(User $user) { // Return static JSON for request which // contains "application/json" in "Accepts" header. return response()->negotiate($user, [ 'application/json' => '{"id":4}', ]); }
默认情况下,包支持 application/json
和 application/xml
。XML格式通过 mleczek/xml
包解析。
扩展
您可以在任何 ServiceProvider
的 boot
方法中扩展支持的内容类型
public function boot(ContentNegotiation $negotiator) { // The ContentNegotiation facade is also available $negotiator->extend('application/json', function () { return new JsonHandler(); }); }
第一个参数接受应使用指定处理程序的内容类型(或内容类型的数组)。
处理程序必须实现 Mleczek\Negotiator\Contracts\ContentNegotiationHandler
接口。
贡献
感谢您考虑贡献!如果您想修复错误或提出新功能,您可以提交一个Pull Request。
许可证
此库采用MIT许可证。