Skip to content
Antares

Bindings & Singletons

Bind an interface (or any class) to a concrete class name. make() then resolves the concrete instead:

$container->bind(LoggerInterface::class, FileLogger::class);
$logger = $container->make(LoggerInterface::class); // a FileLogger

bind() takes a class name, not a factory. The concrete is resolved like any other class: autowired (a new instance each time), or shared if you also registered it with singleton() or scoped().

Register a class as a singleton with a factory closure. The factory runs on the first make() and the same instance is returned on every later 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),
);
});

scoped() works like singleton(), but the shared instance is thrown away when clearScoped() is called:

$container->scoped(RequestContext::class, fn () => new RequestContext());
$a = $container->make(RequestContext::class);
$b = $container->make(RequestContext::class); // same instance as $a
$container->clearScoped();
$c = $container->make(RequestContext::class); // a fresh instance

The framework calls clearScoped() at the start of every request, before any middleware runs, so middleware and controllers in the same request share one instance. Use scoped() for anything that holds per-request state (the current user, tenant, request ID) so it never leaks into the next request under a worker runtime such as Swoole or FrankenPHP. Under PHP-FPM, scoped() and singleton() behave the same, because the process ends after each request.

When the same class is registered more than one way, make() uses the first match:

  1. A singleton that has already been built
  2. scoped()
  3. singleton()
  4. bind()
  5. Autowiring