A big refactoring job at my workplace has led me to review some of the ViewHelpers we are having in one of our core applications. These helpers where targeting different types of properties resulting in the use of several view helpers for a single view and the same view helper being used by multiple (unrelated) views. This results in a high coupling whereas we would like a lower coupling.
In my opinion we have improved by implementing a series of Decorator Pattern for the individual entities.
1<?php 2#./module/App/src/View/Helper/UserDecorator.php 3 4namespace App\View\Helper; 5 6use Zend\View\Helper\AbstractHelper; 7 8class UserDecorator extends AbstractHelper 9{10 /** @var User */11 private $user;12 13 /**14 * Clone the user decorator with the provided user15 * @param User $user16 * @return UserDecorator17 */18 public function __invoke(User $user)19 {20 $clone = clone $this;21 $clone->user = $user;22 23 return $clone;24 }25 26 /**27 * Get the full name of the user28 * @return string29 */30 public function getFullName()31 {32 return sprintf(33 '%s %s',34 $this->user->getFirstName(),35 $this->user->getLastName()36 );37 }38}
Some plumping needs to be done in order to get the decorator available in the view:
1<?php 2# ./module/App/config/module.config.php 3 4use App\View\Helper; 5 6return [ 7 'view_helpers' => [ 8 'invokables' => [ 9 'userDecorator' => Helper\UserDecorator::class10 ]11 ]12];
Using it in the view is rather simple:
1<?php2#./module/App/view/user/overview.php3$user = $this->userDecorator($this->user);4 5printf('Full name: %s', $user->getFullName());