PHP code example of sanmai / di-container

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

    

sanmai / di-container example snippets


use DIContainer\Container;

$container = new Container();

// Automatic resolution - no configuration needed
$service = $container->get(YourService::class);

// Use builder objects for complex construction, or construct the dependencies directly - your choice
$container = new Container([
    ComplexObject::class => fn(Container $container) => new ComplexObject(
        $container->get(LoggerInterface::class),
        $container->get(AnotherProvider::class)->getValue()
    ),
    DatabaseInterface::class => fn(Container $container) =>
        $container->get(DatabaseBuilder::class)->build(),
]);

// Set additional dependencies on the fly
$container->set(LoggerInterface::class, fn() => new FileLogger('debug.log'));

$service = $container->get(ServiceNeedingDatabase::class); // Auto-injects database

use DIContainer\Builder;

/**
 * Builder that accepts injectable dependencies.
 *
 * @implements Builder<DatabaseInterface>
 */
class DatabaseBuilder implements Builder
{
    public function __construct(
        private readonly ConfigProvider $config,
        private readonly Logger $logger
    ) {}

    public function build(): DatabaseInterface
    {
        return new MySQLDatabase(
            $this->config->getDatabaseHost(),
            $this->config->getDatabaseCredentials(),
            $this->logger
        );
    }
}

// 1. Direct class name, if the class implements DIContainer\Builder interface
$container = new Container([
    DatabaseInterface::class => DatabaseBuilder::class,
]);

// 2. Explicit closure - what will the container do under the hood
$container = new Container([
    DatabaseInterface::class => fn(Container $container) => $container->get(DatabaseBuilder::class)->build(),
]);

// Register with a dotted ID - type validation is skipped
$container = new Container(
    values: [
        LoggerInterface::class => FileLogger::class,
    ],
    bindings: [
        'app.repository' => fn() => new CachedRepository(new DatabaseRepository()),
        'app.cache' => CacheBuilder::class,
    ]
);

// Or add bindings on the fly
$container->bind('app.mailer', fn() => new MyMailer());

// Builder classes work too
$container->bind('app.session', SessionBuilder::class);

$repository = $container->get('app.repository');

$logger = new FileLogger('app.log');
$container->inject(LoggerInterface::class, $logger);