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,
    Service,
};

enum Services implements Service
{
    case connection;
    case connectionA;
    case connectionB;

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

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

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

$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