sorciulus/simple-factory

This library generate object from class name

2.1.8 2019-09-04 17:11 UTC

This package is auto-updated.

Last update: 2024-11-05 04:32:41 UTC


README

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

This library has been designed to make it easy to generate value objects. You can set the parameters of the object without knowing in what order it is passed to the constructor. This library will be useful if you have so many parameters to pass to the constructor. By default all parameter will be set to null. If parameter is class (dependency injection) this library will attempt to create an empty object and pass it as a parameter.

Installation

Via Composer:

composer require sorciulus/simple-factory

Usage

<?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();

You can factory object by the same initialized object, all property setter will be set at new factory object

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

If you want to set all the missing parameters to null, pass as a true parameter in the constructor

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

In alternative you can create a factory object from static method create

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

License

This Library is released under the MIT License. Please see License File for more information.