sorciulus/simple-factory

此库可以从类名生成对象

2.1.8 2019-09-04 17:11 UTC

This package is auto-updated.

Last update: 2024-09-05 04:10:04 UTC


README

Packagist Scrutinizer Code Quality Code Intelligence Status Maintainability Software License Build Status

这个库被设计成便于生成值对象。您可以在不知道构造函数参数传递顺序的情况下设置对象的参数。如果您有很多参数要传递给构造函数,此库将非常有用。默认情况下,所有参数都将设置为null。如果参数是类(依赖注入),此库将尝试创建一个空对象并将其作为参数传递。

安装

通过Composer

composer require sorciulus/simple-factory

用法

<?php
require_once 'vendor/autoload.php';

use SimpleFactory\SimpleFactory;

class Publisher
{
    /**
     * The name of publisher
     *
     * @var string
     */
    private $name;

    /**
     * The city of publisher
     *
     * @var string|null
     */
    private $city;

    /**
     * @param string $name
     */
    public function __construct(string $name, ?string $city)
    {
        $this->name = $name;
    }

    /**
     * Get the name of publisher
     *
     * @return string
     */
    public function getName() : string
    {
        return $this->name;
    }

    /**
     * Get the city of publisher
     *
     * @return string|null
     */
    public function getCity() :?string
    {
        return $this->city;
    }
}

$factory   = new SimpleFactory(Publisher::class);
$publisher = $factory->setName('MyPublisher')->setCity('London')->make();

您可以通过相同的初始化对象创建工厂对象,所有属性设置器都将设置在新工厂对象上

$otherFactory = new SimpleFactory(Publisher::class);
$newPublisher = $otherFactory->with($publisher)->make();

如果您想将所有缺失的参数设置为null,请将true作为参数传递给构造函数

$otherFactory = new SimpleFactory(Publisher::class, true);
$newPublisher = $otherFactory->make();

或者,您还可以通过静态方法create创建工厂对象

$newPublisher = SimpleFactory::create(Publisher::class)->setName('MyPublisher')->setCity('London')->make();

许可证

此库根据MIT许可证发布。请参阅许可证文件以获取更多信息。