tonicforhealth / model-transformer
对象转换的简单抽象
v1.0.1
2017-05-18 08:45 UTC
Requires (Dev)
- phpspec/phpspec: ~2.3
This package is not auto-updated.
Last update: 2024-09-14 18:53:01 UTC
README
对象转换的简单抽象。
安装
通过composer要求依赖项
$ composer require tonicforhealth/model-transformer
用法
可能的用例
- 将领域模型层从视图或表示层分离,但仍然保持对象。
- 将领域模型从资源表示(在RESTful应用程序中)分离。
假设,有两个 领域对象
<?php class Product { /** * @var string */ private $name; /** * @var Category */ private $category; // ... /** * @return string */ public function getName() { return $this->name; } /** * @return Category */ public function getCategory() { return $this->category; } } class Category { /** * @var string */ private $name; // ... /** * @return string */ public function getName() { return $this->name; } }
和一个 表示对象,可用于表示层
<?php class ProductPresentation { /** * @var string */ private $name; /** * @var string */ private $categoryName; /** * @var int */ private $purchasedCount; // ... /** * @return string */ public function getName() { return $this->name; } /** * @return string */ public function getCategoryName() { return $this->categoryName; } /** * @return string */ public function getPurchasedCount() { return $this->purchased; } }
有许多将 Product
和 Category
对象转换为 ProductRepresentation
的解决方案
- 只需在需要的位置根据
Product
和Category
创建ProductRepresentation
; - 创建
ProductRepresentation
的工厂; - 等等。
此库为此问题提供了简单而简洁的解决方案
- 为对象创建转换器。
- 将其注册到转换器管理器或单独使用。
可能的 ProductRepresentation
转换器
<?php class ProductToProductRepresentationModelTransformer implements ModelTransformerInterface { /** * @var ProductRepository */ private $productRepository; // ... /** * {@inheritdoc} */ public function supports($object, $targetClass) { return ($object instanceof Product) && is_a($targetClass, ProductRepresentation::class, true); } /** * {@inheritdoc} */ public function transform($object, $targetClass) { /** @var Product $product */ $product = $object; $purchasedCount = $this->productRepository->computePurchasedCount($product); return new ProductRepresentation( $product->getName(), $product->getCategory()->getName(), $purchasedCount ); } }
注册
<?php $priority = 0; $modelTransformer->addTransformer($productToProductRepresentationModelTransformer, $priority = 0);
可选的优先级整数(越高越重要,因此转换器将比其他转换器先触发),它决定了转换器何时与其他转换器触发(默认为0)。
在任何地方使用
<?php $productRepresentation = $modelTransformer->transform($product, ProductRepresentation::class);
如果您有简单的转换规则,则可以使用 ObjectTransformerInterface。作为奖励,转换将运行得更快。
规范
所有实际文档都是位于 /spec
目录中的可运行库规范。
为确保库没有损坏,请运行(在库目录下)
bin/phpspec run