Presenters

Presenters are decorators that add behaviour to entities for view formatting.

Action Models may wrap entities that are available for the view by their presenters. This allows to move logic from the view to the presenter.

<?php
namespace App\Presenter;

use 
Gobline\Presenter\Presenter;
use 
Gobline\Presenter\PresenterFactory;
use 
App\Model\Entity\User;

class 
UserPresenter extends Presenter
{
    public function 
__construct(User $subject) {
        
parent::__construct($subject);
    }

    public function 
getFullName()
    {
        return 
$this->subject->getFirstName().' '.$this->subject->getLastName();
    }

    public function 
getAddresses()
    {
        return new 
AddressCollectionPresenter(
            
$this->subject->getAddresses(), new PresenterFactory());
    }
}

In the Action Model:

<?php
    
public function getUser()
    {
        
$user $this->repository->find($this->id);

        return new 
UserPresenter($user);
    }

In most cases, the presenter will need dependencies, and thus can't be simply instantiated from the Action Model as in the snippet above. You will rather inject a presenter factory into the Action Model.

<?php
namespace App\Presenter;

use 
Gobline\Presenter\PresenterFactoryInterface;

class 
UserPresenterFactory implements PresenterFactoryInterface
{
    public function 
__construct(/* dependencies */)
    {
        
// ...
    
}

    public function 
createPresenter($user)
    {
        return new 
UserPresenter($user/* dependencies */);
    }
}
<?php
    
public function __construct(
        
UserRepository $repository,
        
UserPresenterFactory $userPresenterFactory,
        
// ...
    
) {
        
$this->repository $repository;
        
$this->userPresenterFactory $userPresenterFactory;
        
// ...
    
}

    public function 
getUser()
    {
        
$user $this->repository->find($this->id);

        return 
$this->userPresenterFactory->createPresenter($user);
    }