德国里斯切尔 / 对象创建器
递归初始化和实例化(数据结构)对象
v0.1.0
2021-05-21 05:10 UTC
Requires
- php: >=7.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-12 06:14:15 UTC
README
对象创建器可用于从表示数据结构的类中实例化和初始化对象。可以添加知道如何实例化特定类对象的实例化程序。这样就可以确保所有对象都得到适当的实例化。
用法
use Drieschel\ObjectCreator\ObjectCreator; use Drieschel\ObjectCreator\Instantiator\DateTimeInstantiator; // Example data from various source $data = [ 'int' => 42, 'float' => 0.7, 'string' => 'yeeeehaaa', 'bool' => true, 'datetime' => 'Sat Jan 30 1988 12:22:22 GMT+0100' ]; // Example data structure class class Entity { protected int $int; protected float $float; protected string $string; protected bool $bool; protected \DateTimeInterface $datetime; public function __construct(int $int, string $string) { $this->int = $int; $this->string = $string; } public function setFloat(float $float): self { $this->float = $float; return $this; } public function setBool(bool $bool): self { $this->bool = $bool; return $this; } public function setDatetime(\DateTimeInterface $datetime): self { $this->datetime = $datetime; return $this; } } // Instantiate the creator $creator = new ObjectCreator(); // Add a class mapping for arguments from type DateTimeInterface. // All arguments from type DateTimeInterface will be instantiated as DateTimeImmutable $creator->setClassMapping(\DateTimeInterface::class, \DateTimeImmutable::class); // Register a DateTime instantiator which knows how to // instantiate objects that implements the DateTimeInterface $creator->registerInstantiator(new DateTimeInstantiator()); // Instantiate an object $entity = $creator->instantiate(Entity::class, $data); // Initialize an object $creator->initialize($entity, $data); // Or instantiate and initialize an object together $entity = $creator->instantiateAndInitialize(Entity::class, $data);