PHP code example of free-elephants / di

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

    

free-elephants / di example snippets


$components = reeElephants\DI\InjectorBuilder)->buildFromArray($components);
$app = $di->createInstance(\YourApplication::class);
$app->run();



return [
    'instances' => [
        \PDO::class => new \PDO(getenv('DB_DNS'), getenv('DB_USER'), getenv('DB_PASS')),
    ],
    'register' => [
        \YourApplication::class,
        \ControllerFactory::class,
        \SomeService::class,
        \AnotherService::class,
        \Psr\Log\LoggerInterface::class => \Symfony\Component\Console\Logger\ConsoleLogger::class,
    ],
    'callable' => [ 
        // if function provided as key value
        // first argument passed to callable is psr container
        // second is key
        Foo::class => function(\Psr\Container\ContainerInterface $container, string $key) {
           return (new Foo())->setSomething($container->get('something'));
        },
        // if array provided as key value
        // first argument passed to callable is psr container
        // remaining element as ...args tail
        Bar::class => [ // array where first element is callable, other is values for last arguments
            function(\Psr\Container\ContainerInterface $container, $firstArg, string $secondArg) {
                return new Bar($firstArg, $secondArg);
            },
            100,
            500,
        ],       
    ],
    'loggers' => [
       // For suitable logger injections use map, where keys are your services, that implement LoggerAwareInterface
       // and value is logger instances
       LoggerAwareClass::class        => $logger,
       AnotherLoggerAwareClass::class => $anotherLogger,
    ],   
];


// getenv('ENV') -> 'test'
$components = (new \FreeElephants\DI\EnvAwareConfigLoader(__DIR__ . '/config', 'ENV'))->readConfig('components');
$di = (new \FreeElephants\DI\InjectorBuilder)->buildFromArray($components);