popcorn4dinner/presenters

展示者模式的非意见化实现

0.1.2 2018-04-19 13:04 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:48:27 UTC


README

安装

composer require popcorn4dinner/presenters

使用

展示者模式背后的想法是将展示逻辑与您的领域模型分离。作为副作用,您也仅公开需要的函数,因此向渲染过程公开的最小可能接口。

示例

简单的用户和展示者类

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';
    }
}

示例用法

控制器

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;
    }
}

视图

<div>
 Name: {% $user->getFullName() %} // Florian Tylman
 Age: {% $user->getAge() %} // 13
</div>