ekvedaras/class-factory

通过构造函数参数创建对象的工厂

v1.2.0 2023-02-15 17:32 UTC

This package is auto-updated.

Last update: 2024-09-08 22:51:22 UTC


README

Latest Version on Packagist Tests Total Downloads

一个直接将每个属性传递给构造函数的工厂类。这样,您的类不需要处理接收到的数组来创建自身,也不涉及反射魔法。这对于创建类似值对象、实体、DTO等普通类非常有用。

安装

您可以通过composer安装此包。

composer require --dev ekvedaras/class-factory

PhpStorm插件

为PhpStorm提供自动完成和重构功能。

用法

use EKvedaras\ClassFactory\ClassFactory;
use EKvedaras\ClassFactory\ClosureValue;

class Account {
    public function __construct(
        public readonly int $id,
        public string $name,
        public array $orders,
        public \Closure $monitor,
    ) {
    }
}

/** @extends ClassFactory<Account> */
class AccountFactory extends ClassFactory {
    protected string $class = Account::class;
    
    protected function definition(): array
    {
        return [
            'id' => 1,
            'name' => 'John Doe',
            'orders' => [
                OrderFactory::new()->state(['id' => 1]),
                OrderFactory::new()->state(['id' => 2]),
            ],
            'monitor' => new ClosureValue(fn () => true),
        ];
    }

    public function johnSmith(): static
    {
        return $this->state([
            'id' => 2,
            'name' => 'John Smith',
        ]);
    }
}

$account = AccountFactory::new()
    ->johnSmith()                                                           // Can use predefiened states
    ->state(['name' => 'John Smitgh Jnr'])                                  // Can override factory state on the fly
    ->state(['name' => fn (array $attributes) => "{$attributes['name']}."]) // Can use closures and have access to already defined attributes
    ->after(fn (Account $account) => sort($account->orders))                // Can modify constructed object after it was created
    ->state(['monitor' => new ClosureValue(fn () => false)])                // Can set state of closure type properties using `ClosureValue` wrapper
    ->make(['id' => 3])                                                     // Can provide final modifications and return the new object

自定义类创建

如果您不想通过直接将属性传递给构造函数来创建类,您可以在工厂中重写newInstance方法并更改其行为。

protected function newInstance(array $properties): object
{
    return Account::makeUsingProperties($properties);
}

测试

composer test

变更日志

请参阅变更日志以获取有关最近更改的更多信息。

贡献

请参阅贡献指南以获取详细信息。

安全漏洞

请参阅我们的安全策略了解如何报告安全漏洞。

致谢

许可

MIT许可(MIT)。请参阅许可文件以获取更多信息。