da2e/simple-factory

Mini-package implementing and providing a Simple Factory (design pattern) functionality.

v1.0.0 2017-05-21 16:39 UTC

This package is not auto-updated.

Last update: 2024-05-31 17:56:40 UTC


README

Build Status

SimpleFactory is a mini-package implementing Simple Factory design pattern and providing its functionality.

How to use

<?php

use Da2e\SimpleFactory\SimpleFactory;

$factory = new SimpleFactory();
$factory->create(TheObjectYouNeedToCreate::class, ['optional', 'array', 'of', 'constructor', 'args']);

The order of the constructor arguments matters!

To automate the process of creating homogeneous objects with the same constructor arguments, you could simply create a wrapper for the SimpleFactory and pass the required arguments to its constructor, as follows:

<?php

use Da2e\SimpleFactory\SimpleFactory;

class MySimpleFactory extends SimpleFactory
{
    private $dependency;
    
    public function __construct($dependency)
    {
        $this->dependency = $dependency;
    }
    
    /**
     * {@inheritdoc}
     */
    public function create(string $class, array $constructorArgs = [])
    {
        parent::create($class, array_merge([$this->dependency], $constructorArgs));
    }
}

$factory = new MySimpleFactory('foobar');
$factory->create(TheObjectYouNeedToCreate1::class);
$factory->create(TheObjectYouNeedToCreate2::class);
$factory->create(TheObjectYouNeedToCreate3::class);

Software requirements

  • PHP >= 7.0

How to install

composer require da2e/simple-factory "1.*"

License

This bundle is under the MIT license.