Usage

Registering Services

Factory Functions

Pass a callable that receives the container:

$container->bind(Mailer::class, function (Container $c) {
    return new Mailer(
        $c->get(TransportInterface::class),
        $c->get(Logger::class)
    );
});

Class Names

Bind interface to concrete class (auto-wired):

$container->bind(UserRepositoryInterface::class, UserRepository::class);

Singletons

Use singleton() or chain ->share():

// Method 1
$container->singleton(Config::class, fn() => new Config());

// Method 2
$container->bind(Config::class, fn() => new Config())->share();

Resolving Services

Basic Resolution

$mailer = $container->get(Mailer::class);

Checking Existence

if ($container->has(Logger::class)) {
    $logger = $container->get(Logger::class);
}

Auto-wiring

The container automatically resolves constructor dependencies:

class OrderService {
    public function __construct(
        private OrderRepository $repo,
        private PaymentGateway $gateway,
        private Logger $logger
    ) {}
}

// All dependencies resolved automatically
$service = $container->get(OrderService::class);

Auto-wiring Rules

  1. Type-hinted class/interface ? Resolved from container
  2. Built-in types with defaults ? Uses default value
  3. Nullable types ? Uses null if not found
  4. No type hint with default ? Uses default value

Aliases

$container->alias('config', ConfigRepository::class);
$container->alias('log', Logger::class);

$config = $container->get('config');

Tagging

Group and retrieve services:

// Register tagged services
$container->bind(EmailNotifier::class)->addTag('notifier');
$container->bind(SmsNotifier::class)->addTag('notifier');
$container->bind(PushNotifier::class)->addTag('notifier');

// Get all notifiers
$notifiers = $container->tagged('notifier');
foreach ($notifiers as $notifier) {
    $notifier->send($message);
}

Removing Services

$container->forget(Logger::class);

Listing Services

$serviceIds = $container->keys();