pustato / presenter
Presenter pattern for PHP
Installs: 1 937
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: >=7.0.0
Requires (Dev)
- phpunit/phpunit: ^6.1
This package is not auto-updated.
Last update: 2025-02-05 22:55:50 UTC
README
The tool to separate logic of models and views.
Install
Require this package with composer
composer require pustato/presenter
Usage
Implement Pustato\Presenter\Contracts\PresentableContract
interface.
<?php use Pustato\Presenter\Contracts\PresentableContract; class SomeModel implements PresentableContract { /** @var int */ public $id; /** @var string */ public $firstName; /** @var string */ public $lastName; /** @var \DateTime */ public $birthDate; public function getPresentableAttribute(string $name) { return property_exists($this, $name) ? $this->$name : null; } }
Make presenter class.
<?php use Pustato\Presenter\AbstractPresenter; use Pustato\Presenter\Contracts\PresentableContract; class SomeModelPresenter extends AbstractPresenter { protected function attributes(PresentableContract $presentable): array { return [ 'fullName' => $presentable->firstName.' '.$presentable->lastName, // callable will be calculated at first call and cached. 'age' => function($presentable) { return (int) $presentable ->birthDate ->diff(new \DateTime('now')) ->y; } ]; } }
Create presenter instance and use in views.
$presenterInstance = new SomeModelPresenter($modelInstance)
<p><strong>ID</strong>: <?= $presenterInstance->id ?></p> <p><strong>Full name</strong>: <?= $presenterInstance->fullName ?></p> <p><strong>Age</strong>: <?= $presenterInstance->age ?></p>