mleczek / laravel-negotiator by mleczek

Content negotiation for Laravel API
11
1
2
Package Data
Maintainer Username: mleczek
Maintainer Contact: mleczek.wojtek@gmail.com (Wojciech Mleczek)
Package Create Date: 2017-01-12
Package Last Update: 2017-01-21
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-04-17 15:08:08
Package Statistics
Total Downloads: 11
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 1
Total Watchers: 2
Total Forks: 0
Total Open Issues: 0

Content negotiation for Laravel API

Build Status Latest Stable Version License

Installation

Require this package with composer:

composer require mleczek/laravel-negotiator

In config/app.php add the NegotiatorServiceProvider:

'providers' => [
    Mleczek\Negotiator\NegotiatorServiceProvider::class,
]

Usage

Package provide negotiate macro for ResponseFactory:

public function show(User $user)
{
    return response()->negotiate($user);
}

The same result can be achieved using Mleczek\Negotiator\ContentNegotiation class:

public function __construct(ContentNegotiation $cn)
{
    $this->cn = $cn;
}

public function show(Request $request, User $user)
{
    return $cn->negotiate($request, $user);
}

For both negotiate method and macro there is also one parameter which override result for specified content types:

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}',
    ]);
}

By default package support application/json and application/xml. XML format is resolved using mleczek/xml package.

Extending

You can extend supported content types in boot method of any of your ServiceProvider:

public function boot(ContentNegotiation $negotiator)
{
    // The ContentNegotiation facade is also available
    $negotiator->extend('application/json', function () {
        return new JsonHandler();
    });
}

The first parameter accept content type (or array of content types) for which the specified handler should be used.

Handler must implement the Mleczek\Negotiator\Contracts\ContentNegotiationHandler interface.

Contributing

Thank you for considering contributing! If you would like to fix a bug or propose a new feature, you can submit a Pull Request.

License

The library is licensed under the MIT license.