PHP code example of innmind / di

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

    

innmind / di example snippets


use Innmind\DI\{
    Builder,
    Container,
};

$container = Builder::new()
    ->add('connection', fn(Container $get) => new ConnectionPool( // imaginary class
        $get('connection_a'),
        $get('connection_b'),
    ))
    ->add('connection_a', fn() => new \PDO('mysql://localhost'))
    ->add('connection_B', fn() => new \PDO('mysql://docker'))
    ->build();

$connection = $container('connection');
$connection instanceof ConnectionPool; // true

use Innmind\DI\Service;

/**
 * @template S
 * @implements Service<S>
 */
enum Services implements Service
{
    case connection;
    case connectionA;
    case connectionB;

    /**
     * @return self<ConnectionPool>
     */
    public static function connection(): self
    {
        /** @var self<ConnectionPool> */
        return self::connection;
    }

    /**
     * @internal
     *
     * @return self<\PDO>
     */
    public static function connectionA(): self
    {
        /** @var self<\PDO> */
        return self::connectionA;
    }

    /**
     * @internal
     *
     * @return self<\PDO>
     */
    public static function connectionB(): self
    {
        /** @var self<\PDO> */
        return self::connectionB;
    }
}

use Innmind\DI\{
    Builder,
    Container,
};

$container = Builder::new()
    ->add(Services::connection, fn(Container $get) => new ConnectionPool( // imaginary class
        $get(Services::connectionA),
        $get(Services::connectionB),
    ))
    ->add(Services::connectionA, fn() => new \PDO('mysql://localhost'))
    ->add(Services::connectionB, fn() => new \PDO('mysql://docker'))
    ->build();

$connection = $container(Services::connection);
$connection instanceof ConnectionPool; // true