locomotivemtl / charcoal-presenter
The missing charcoal layer between models and views.
Installs: 1 388
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 16
Forks: 1
Open Issues: 0
Requires
- php: >=5.6.0 || >=7.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^5.7 || ^6.5
- squizlabs/php_codesniffer: ^3.0
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);