popcorn4dinner / presenters
A non-opinionated implementation of the presenter pattern
0.1.2
2018-04-19 13:04 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ~7
This package is not auto-updated.
Last update: 2025-04-13 08:43:15 UTC
README
Installation
composer require popcorn4dinner/presenters
Usage
The idea behind presenters is to separate the presentation logic from your domain models. As a side effect you also only expose only needed functions and therefore the smallest possible interface to the render process.
Example
Simple user and Presenter class
class SimpleUser { private $firstName = "Florian"; private $lastName = "Thylman"; private $age = 13; public function getFirstName() { return $this->firstName; } public function getLastName() { return $this->lastName; } public function getAge() { return $this->age; } public function setAge($newAge) { $this->age = $newAge; } }
class ExamplePresenter extends AbstractPresenter { protected const DELEGATED_METHODS = ['getFirstName', 'getLastName']; public function getFullName() { return $this->getFirstName() . ' ' . $this->getLastName(); } public function getAge() { return $this->original->getAge() . ' years'; } }
Example usage
Controller:
class UserController { public function view(Request $request, FindUserHandler $handler, \Twig_Environment $twig) { $command = $this->commandPopulator->populate(new FindUser(), $request); $user = $handler->execute($command, $user); $response = new Response( $twig->render( 'users/view.twig', [ 'user' => new UserPresenter($user) ] ) ); return $response; } }
View:
<div> Name: {% $user->getFullName() %} // Florian Tylman Age: {% $user->getAge() %} // 13 </div>