Bindings & Singletons
Binding Interfaces
Section titled “Binding Interfaces”Bind an interface to a concrete implementation. Every call to make(InterfaceClass::class) will resolve to the bound concrete:
$container->bind(LoggerInterface::class, FileLogger::class);
$logger = $container->make(LoggerInterface::class);Singletons
Section titled “Singletons”Register a class as a singleton with a factory closure. The same instance is returned on every make() call. Use this for anything that needs primitive constructor arguments (like values from .env):
$container->singleton(Database::class, function (Container $container) { return new Database( host: $_ENV['DB_HOST'], port: (int) $_ENV['DB_PORT'], name: $_ENV['DB_DATABASE'], );});
$db1 = $container->make(Database::class);$db2 = $container->make(Database::class);
assert($db1 === $db2);The factory receives the container instance, so you can resolve other dependencies inside it:
$container->singleton(UserRepository::class, function (Container $container) { return new UserRepository( db: $container->make(Database::class), );});