locomotivemtl/charcoal-presenter

The missing charcoal layer between models and views.

0.3.2 2020-07-02 15:23 UTC

This package is auto-updated.

Last update: 2024-10-29 04:53:34 UTC


README

The missing layer between models and views. The Presenter takes any data model (objects or arrays) and serializes them into a presentation array according to a transformer.

Usage

Simplest usage, with a simple array transformer:

$presenter = new Presenter([
    'id',
    'name',
    'display_date'
]);

$model = $factory->create(Model::class);
$viewData = $presenter->transform($model);

A callable is preferred if operations on objects are required:

The callable signature must array: callable(mixed $model).

$presenter = new Presenter(function($model) {
    return [
        'id',
        'name',
        'display_date' => $model->date->format('Y-m-d')
    ];
});

$model = $factory->create(Model::class);
$viewData = $presenter->transform($model);

Common transformers (or customizable transformers, shown below) should be self-contained inside their own Callable classes:

class MyTransformer
{
    /**
     * @var string $dateFormat
     */
    private $dateFormat;
    
    /**
     * @param string $dateFormat The date format.
     */
    public function __construct($dateFormat)
    {
        $this->dateFormat = $dateFormat;
    }

    /**
     * @param mixed $model The model to transform.
     * @return array
     */
    public function __invoke($model)
    {
        $displayDate = $obj->date->format($this->dateFormat);
        return [
            'id',
            'name',
            'display_date'=>$displayDate
        ];
    }
}

$presenter = new Presenter(new MyTransformer('Y-m-d'));

$model = $factory->create(Model::class);
$viewData = $presenter->transform($model);