gobline / presenter
展示组件
v2.0.0
2015-12-03 09:17 UTC
Requires
- php: >=5.6.0
- doctrine/collections: ^1.3
This package is auto-updated.
Last update: 2024-09-12 18:30:43 UTC
README
展示组件允许您使用视图所需的方法来装饰您的模型对象。一个典型的例子是用来展示展示器的用法,就是一个展示器方法将模型中的日期格式化为用户更易读的格式。
Gobline\Presenter\Presenter
通过用 Gobline\Presenter\Presenter
实例装饰您的模型对象,您将能够像访问公共字段一样访问私有/受保护的字段,只要定义了获取器。
class Property { protected $price; protected $nbRooms; protected $livingArea; protected $publicationDate; public function __construct($price, $nbRooms, $livingArea) { $this->price = $price; $this->nbRooms = $nbRooms; $this->livingArea = $livingArea; $this->publicationDate = new \DateTime(); } public function getPrice() { return $this->price; } public function getNbRooms() { return $this->nbRooms; } public function getLivingArea() { return $this->livingArea; } public function getPublicationDate() { return $this->publicationDate; } } $property = new Property(650, 1, 120); $property = new Gobline\Presenter\Presenter($property);
<label>Living area:</label><?= $property->livingArea ?>
这通过 PHP 的魔法方法 __get
和 __call
来实现。
为了给模型对象添加用于视图格式化的行为,您需要创建自己的展示器
class PropertyPresenter extends Gobline\Presenter\Presenter { public function __construct(Property $subject) { parent::__construct($subject); } public function getPublicationDate() { return $this->subject->getPublicationDate()->format('d/m/Y'); } public function getNbRooms() { $nbRooms = $this->subject->getNbRooms(); if ($nbRooms === 0) { return 'Studio'; } if ($nbRooms === 1) { return $nbRooms.' room'; } return $nbRooms.' rooms'; } } $property = new Property(650, 1, 120); $property = new PropertyPresenter($property);
<label>Living area:</label><?= $property->livingArea ?> <label>Number of rooms:</label><?= $property->nbRooms ?> <label>Publication date:</label><?= $property->publicationDate ?>
Gobline\Presenter\PresenterFactoryInterface
当您的展示器需要依赖项时,展示器工厂非常有用。您在工厂中一次性注入依赖项,工厂将按需创建展示器,同时包含所有必需的依赖项。
use Gobline\Translator\Translator; class PropertyPresenterFactory implements Gobline\Presenter\PresenterFactoryInterface { protected $translator; public function __construct(Translator $translator) { $this->translator = $translator; } public function createPresenter($property) { return new PropertyPresenter($property, $this->translator); } }
然后,通常将此工厂注入到将装饰的模型实例返回给视图的对象中。现在,该对象可以返回装饰的模型实例,如下所示
$property = $this->propertyPresenterFactory->createPresenter($property);
Gobline\Presenter\CollectionPresenter
当视图需要显示来自模型实例数组的模型数据时,我们需要将此数组包装起来,以便在每次数组访问时返回我们的展示器(装饰的模型实例)。集合包装器需要一个展示器工厂来返回正确的展示器。
$results = $this->orm->findAll(); $results = new Gobline\Presenter\CollectionPresenter($results, $this->propertyPresenterFactory);
Gobline\Presenter\PresenterTrait
展示器特性允许您将私有/受保护的属性访问为公共属性。
安装
您可以使用依赖管理工具 Composer 安装展示组件。运行 require 命令以解析和下载依赖项
composer require gobline/presenter