PHP code example of milpa / container

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

    

milpa / container example snippets


use Milpa\Container\DIContainer;

class Logger
{
    public function log(string $message): void
    {
        echo $message . "\n";
    }
}

class Greeter
{
    public function __construct(private Logger $logger)
    {
    }

    public function greet(string $name): void
    {
        $this->logger->log("Hello, {$name}!");
    }
}

$container = new DIContainer();

// Auto-wiring: no registerService() call needed — Greeter's constructor
// dependency (Logger) is resolved recursively.
$greeter = $container->get(Greeter::class);
$greeter->greet('World'); // "Hello, World!"

// get() caches auto-resolved classes as singletons.
$container->get(Greeter::class) === $greeter; // true

// tryGet() never throws — null for anything unregistered/unresolvable.
$container->tryGet('Nonexistent\Service'); // null

// Explicit registration still wins over auto-wiring for the same id.
$container->registerService(Logger::class, new Logger());

class A { public function __construct(public B $b) {} }
class B { public function __construct(public A $a) {} }

$container->get(A::class);
// throws Milpa\Exceptions\CircularDependencyException:
// "Circular dependency detected while resolving: A -> B -> A."