PHP code example of locomotivemtl / charcoal-factory

1. Go to this page and download the library: Download locomotivemtl/charcoal-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/ */

    

locomotivemtl / charcoal-factory example snippets


$factory = new \Charcoal\Factory\GenericFactory([
    // Ensure the created object is a Charcoal Model
    'base_class' => '\Charcoal\Model\ModelInterface',

    // An associative array of class map (aliases)
    'map' => [
        'foo' => '\My\Foo',
        'bar' => '\My\Bar'
    ],

    // Constructor arguments
    'arguments' => [
        $dep1,
        $dep2
    ],

    // Object callback
    'callback' => function (&obj) {
        $obj->do('foo');
    }
]);

// Create a "\My\Custom\Baz" object with the given arguments + callbck
$factory->create('\My\Custom\Baz');

// Create a "\My\Foo" object (using the map of aliases)
$factory->create('foo');

// Create a "\My\Custom\FooBar" object with the default resolver
$factory->create('my/custom/foo-bar');

$factory = new GenericFactory([
    'map' => [
        'foo' => '\My\Foo',
        'bar' => '\My\Bar'
    ]
]);

// Create a `\My\Foo` instance
$obj = $factory->create('foo');

$factory = new GenericFactory([
    'base_class' => '\My\Foo\BaseClassInterface'
]);

$factory = new GenericFactory([
    'default_class' => '\My\Foo\DefaultClassInterface'
]);

$factory = new GenericFactory([
    'arguments' => [
        [
            'logger' => $container['logger']
        ],
        $secondArgument
    ]
]);

// $obj is the newly created object
function callback(&$obj);

$factory = new GenericFactory([
    'arguments' => [[
        'logger' => $container['logger']
    ]],
    'callback' => function (&$obj) {
        $obj->foo('bar');
        $obj->logger->debug('Objet instanciated from factory.');
    }
]);