Skip to main content

Container Bindings

Overview

The DomainFlow Container allows you to register (or bind) an identifier — such as a class name, interface, or alias—to a callable or concrete class. When you later request that identifier (via methods like $container->make(...) or $container->get(...)), the container automatically instantiates or retrieves the corresponding object.


Key Binding Methods

bind()

Registers a binding from an abstract identifier to a concrete implementation.

Method Signature:

bind(
string $abstract,
Closure|string|null $concrete,
bool $shared = false
)
ParameterTypeRequired
$abstractstringYes
$concreteClosure, string, or nullYes
$sharedboolOptional

Notes:

  • If $concrete is null, the container uses the abstract identifier as the concrete implementation.
  • If $shared is set to true, the binding behaves like a singleton, ensuring only one instance is created.

singleton()

A shortcut for binding a service as a singleton.

Method Signature:

singleton(
string $abstract,
Closure|string|null $concrete
)
ParameterTypeRequired
$abstractstringYes
$concreteClosure, string, or nullYes

Note:
This is equivalent to calling bind() with the $shared flag set to true.


instance()

Binds an already-created instance to an abstract identifier.

Method Signature:

instance(
string $abstract,
mixed $instance
)
ParameterTypeRequired
$abstractstringYes
$instancemixedYes

Note:
This method stores an existing object, ensuring that the same instance is returned every time the identifier is resolved.


Comparing the Binding Methods

  • bind()
    Defines how the container should create a service. By default, each call to make produces a new instance unless $shared is true.

  • singleton()
    A convenient way to register a binding that should only ever be instantiated once. It internally calls bind() with the shared flag enabled.

  • instance()
    Directly registers an already-instantiated object, making it immediately available as a binding without any further instantiation.


Example Usage

Singleton Binding Example

$container = new Container();

// Register a singleton binding for DatabaseConnection.
// The provided closure will only be executed once.
$container->singleton(DatabaseConnection::class, function () {
return new MySqlConnection();
});

// Both calls to get() return the same instance.
$db1 = $container->get(DatabaseConnection::class);
$db2 = $container->get(DatabaseConnection::class);

In this example, every time you resolve DatabaseConnection::class, the container returns the same instance of MySqlConnection.


Summary

Container bindings in DomainFlow provide a flexible way to manage your service dependencies. Whether you're registering a new service using a factory, setting up a singleton, or storing an existing instance, these methods streamline dependency management and promote cleaner, more modular application code.