rammewerk / hydrator
PHP 8.3+ 强类型 hydrator。
1.1.0
2024-08-22 21:34 UTC
Requires
- php: >=8.3
README
Rammewerk Hydrator 是 PHP 8.3+ 的强类型 hydrator。
安装
通过 composer 安装 Rammewerk Router
composer require rammewerk/hydrator
如何使用
让我们考虑一个简单的实体/dto
final class Product { public string $name = ''; public string $sku = ''; public float $price = 0; public StatusEnum $status = StatusEnum::draft; public ?\DateTime $created_at = null; }
我们可以从数组中填充它
$data = [ 'name' => 'Some product', 'sku' => '1020', 'status' => 'active', ]; $hydrator = new \Rammewerk\Component\Hydrator(Product::class); $product = $hydrator->hydrate($data);
返回一个类型化的实体。
这可能会在自动将数据从数据库转换为实体或从 API 等转换数据时很有用。
优点包括
- 使用实体和类来获得类型安全。
- 使用 hydrator 自动映射类。
- 从你的 IDE 获取类型提示。
- 更好的代码质量。
只读属性
要添加只读属性,它们必须通过构造函数初始化。
class Entity { public function __construct( public readonly int $id ) { } }
允许的属性类型
// Required public string $prop_required; // Optional public string $prop_optional = ''; // Nullable - Hydrator will add null if not defined. public ?string $property; // Boolean - accepts also 1, 0, "on", "off", "1", "true".. public bool $prop = false; // Integer public int $prop = 0; // Float/Number public float $prop; // String public string $prop; // Array public array $prop; // DateTime public ?\DateTime $prop = null; // Enums public Status $status = Statis::draft; // Classes public ?AnotherClass $class = null;
错误处理
try { $hydrator->hydrate(...); } catch (\Rammewerk\Component\Hydrator\Error\HydratorException $e) { // It's an error }