xdevmafia / php-value-object
PHP 的值对象
v1.0.2
2023-04-08 23:42 UTC
Requires
- php: >=7.4
- ext-json: *
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-09 03:02:16 UTC
README
轻松验证、归一化和格式化值。
安装
使用以下命令安装最新版本
$ composer require xdevmafia/php-value-object
基本用法
use XDM\ValueObject\Object\EmailObject; use XDM\ValueObject\Type\StringType; class User { private StringType $username; private EmailObject $email; public function __construct(StringType $username, EmailObject $email) { $this->username = $username; $this->email = $email; } public function getUsername(): StringType { return $this->username; } public function setUsername(StringType $username): void { $this->username = $username; } public function getEmail(): EmailObject { return $this->email; } public function setEmail(EmailObject $email): void { $this->email = $email; } }
try { $username = new StringType('xdevmafia'); $email = new EmailObject('info@xdevmafia.org'); } catch (ConstraintException $e) { throw $e; } $user = new User($username, $email);
类型
可用的 类型 类列表
- IntType
- FloatType
- StringType
- BoolType
- ArrayType
- ObjectType
- MixedType
约束
可用的 约束 类列表
- DateFormat
- Domain
- Enum
- Ip
- IsObject
- Json
- Max
- MaxLength
- Min
- MinLength
- NotEmpty
- NotNull
- Regex
- Url
- Uuid
对象
可用的 对象 类列表
- DateObject
- DateTimeObject
- DomainObject
- EmailObject
- IpObject
- JsonObject
- UrlObject
- UuidObject
对象扩展 *类型 类
use XDM\ValueObject\Constraint\Email; use XDM\ValueObject\Type\StringType; class EmailObject extends StringType { protected function setConstraints(): void { $this->addConstraint(new Email()); } }
您可以创建自己的对象
namespace App\ValueObject; use XDM\ValueObject\Type\StringType; class DeliveryAddressObject extends StringType { }
带有约束
use XDM\ValueObject\Constraint\Regex; use XDM\ValueObject\Type\StringType; class UsernameObject extends StringType { protected function setConstraints(): void { $this->addConstraint(new Regex('[a-z]{3,10}')); } }
您可以创建自己的约束。
可调用的类将返回 bool
值
namespace App\Constraint; use XDM\ValueObject\Constraint; class HexColor implements Constraint { public function __invoke($value): bool { return ctype_xdigit($value); } }
以及使用此约束的对象
namespace App\ValueObject; use App\Constraint\HexColor; use XDM\ValueObject\Type\StringType; class ColorObject extends StringType { protected function setConstraints(): void { $this->addConstraint(new HexColor()); } }