PHP code example of da2e / simple-factory

1. Go to this page and download the library: Download da2e/simple-factory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

da2e / simple-factory example snippets




use Da2e\SimpleFactory\SimpleFactory;

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



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