anfischer / dto
PHP 实现数据传输对象模式(https://martinfowler.com.cn/eaaCatalog/dataTransferObject.html)
v0.1.0
2018-06-25 16:06 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: >=7.2.6
- squizlabs/php_codesniffer: ^2.3
This package is auto-updated.
Last update: 2024-09-27 17:17:44 UTC
README
PHP 实现数据传输对象模式(https://martinfowler.com.cn/eaaCatalog/dataTransferObject.html)。
数据传输对象允许公开属性,并强制验证其数据类型。
此实现支持 PHP 的所有八个基本数据类型
- 字符串
- 整数
- 双精度浮点数 (或 PHP 实现的浮点数)
- 布尔值
- 数组
- 对象
- 空值
- 资源
以及强制布尔值
- 真
和 - 假
安装
通过 Composer
$ composer require anfischer/dto
用法
DTO 类可用于生成通用的数据传输对象,不强制初始化类型,但保证初始化属性的严格类型(例如,首先初始化为字符串的属性不能后来更改为整数)
use Anfischer\Dto\Dto; class GenericDataTransferObject extends Dto { protected $someProperty; protected $anotherProperty; } $dto = new GenericDataTransferObject; $dto->someProperty = 1; $dto->anotherProperty = null; // ERROR - throws InvalidTypeException since type is changed from integer to string $dto->someProperty = 'foo'; // OK - since it was first initialized as null $dto->anotherProperty = 'foo';
DTO 类还允许生成具有类型提示的数据传输对象。
强制类型时,属性不能使用除定义的属性类型之外的类型进行初始化(例如,定义为字符串的属性不能初始化为整数)
use Anfischer\Dto\Dto; class TypeHintedDataTransferObject extends Dto { protected $stringProperty; protected $integerProperty; public function getPropertyType($property): string { switch ($property) { case 'stringProperty': return 'string'; case 'integerProperty': return 'integer'; } } } $dto = new TypeHintedDataTransferObject; $dto->stringProperty = 'foo'; $dto->integerProperty = 1; // ERROR - throws InvalidTypeException since type has to be initialized as string $dto->stringProperty = 1; // ERROR - throws InvalidTypeException since type has to be initialized as integer $dto->integerProperty = 'foo';
最后,DTO 类允许生成具有混合类型提示的数据传输对象。
use Anfischer\Dto\Dto; class TypeHintedDataTransferObject extends Dto { protected $mixedProperty; public function getPropertyType($property): string { switch ($property) { case 'mixedProperty': return 'string|integer|array'; } } } $dto = new MixedTypeHintedDataTransferObject; $dto->mixedProperty = 'foo'; $dto->mixedProperty = 1; $dto->mixedProperty = ['foo', 'bar', 'baz']; // ERROR - throws InvalidTypeException since type has to be either string, integer or array $dto->mixedProperty = 1.1; // ERROR - throws InvalidTypeException since type has to be either string, integer or array $dto->mixedProperty = false;
变更日志
有关最近更改的更多信息,请参阅 CHANGELOG。
测试
$ composer test
贡献
有关详细信息,请参阅 CONTRIBUTING 和 CODE_OF_CONDUCT。
安全
如果您发现任何安全问题,请通过电子邮件 kontakt@season.dk 而不是使用问题跟踪器。
致谢
许可
MIT 许可证(MIT)。有关更多信息,请参阅 许可文件。