rickselby / laravel-auto-presenter-mapper by rickselby

Define presenters in a service provider rather than in the model
5,284
4
2
Package Data
Maintainer Username: rickselby
Maintainer Contact: rick@selby-family.co.uk (Rick Selby)
Package Create Date: 2017-02-21
Package Last Update: 2024-02-03
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-11-19 03:11:39
Package Statistics
Total Downloads: 5,284
Monthly Downloads: 44
Daily Downloads: 0
Total Stars: 4
Total Watchers: 2
Total Forks: 1
Total Open Issues: 0

Laravel Auto Presenter Mapper

PHP 7.0+ Build Status SensioLabs Insight Code Coverage Software License

This is an extension to the excellent laravel-auto-presenter that allows you to define presenters in a service provider or on-the-fly, rather than directly on the model.

Compatibility Chart

| Laravel Auto Presenter Mapper | Laravel | PHP | |----------------------------------------------------------------------------|-----------|--------| | 3.x | 5.5 – 5.6 | 7.1.3+ | | 2.x | 5.1 – 5.5 | 7.0+ | | 1.x | 5.1 – 5.4 | 5.5+ |

Installing

Require the project using Composer:

$ composer require rickselby/laravel-auto-presenter-mapper

Laravel 5.5 will auto-discover the package.

For Laravel 5.1-5.4, you should only add this service provider, not the original laravel-auto-presenter service provider, as this one extends it.

In your config/app.php add this line to your 'providers' array...

RickSelby\LaravelAutoPresenterMapper\AutoPresenterMapperServiceProvider::class,

... and this line to your 'facades' array.

'Presenters' => \RickSelby\LaravelAutoPresenterMapper\Facades\AutoPresenterMapperFacade::class,

Usage

Read the docs at github.com/laravel-auto-presenter/laravel-auto-presenter for the basic use cases.

With this package, instead of altering your models to implement HasPresenter, you can define the presenters in a service provider using the facade. For example:

public function register()
{
    \Presenters::map(User::class, UserPresenter::class);
}

This will work exactly how the laravel-auto-presenter works; any User models passed to a view will be wrapped in UserPresenter.

The map function also takes an array:

public function register()
{
    \Presenters::map([
        User::class => UserPresenter::class,
        ...
    ]);
}

If you wish to declare a mapping on-the-fly, or override a mapping in a specific instance, the facade can be called from anywhere:

public function show(User $user)
{
    \Presenters::map(User::class, UserJSONPresenter::class);
    ...
}

Decoratable

To mimic the Decoratable interface of the parent package, you can call decoratable:

public function register()
{
    \Presenters::decorate(User::class);
    \Presenters::decorate([
        User::class,
        ...
    ]);
    ...
}

License

Laravel Auto Presenter Mapper is licensed under The MIT License (MIT).