Service Container
The Ecommerce\Core\Container class provides dependency injection and service resolution capabilities. It manages class dependencies and performs dependency injection.
Introduction
The Container is the core of the application's dependency injection system. It allows you to bind services, aliases, and instances, and then resolve them with their dependencies automatically injected. This promotes loose coupling and makes testing easier by allowing you to mock dependencies.
Binding Services
These methods allow you to register services and classes into the container.
Bind Service
Bind a class or interface to the container with a closure that resolves the implementation.
Description:
The bind() method registers a binding with the container. Each time the service is resolved, the closure will be executed, returning a new instance of the service. This is useful for services that hold state that shouldn't be shared across the application.
Method Signature:
public function bind(string $name, Closure $resolver)
Parameters:
$name- The class name or interface name to bind$resolver- A Closure that returns the instance of the class
Examples:
// Bind a concrete implementation to an interface
$app->bind(PaymentGatewayInterface::class, function ($app) {
return new StripePaymentGateway(config('stripe.key'));
});
// Bind a class that needs complex setup
$app->bind(ReportGenerator::class, function ($app) {
$pdfLib = new PdfLibrary();
$pdfLib->setOrientation('landscape');
return new ReportGenerator($pdfLib);
});
// Bind with dependencies resolution
$app->bind(OrderService::class, function ($app) {
return new OrderService(
$app->make(OrderRepository::class),
$app->make(EmailService::class)
);
});
Bind Singleton
Bind a class to the container as a singleton (lazy loaded).
Description:
The singleton() method registers a shared binding in the container. The closure is executed only once, the first time the service is resolved. Subsequent calls to resolve the service return the same instance. This is ideal for database connections, configuration services, or expensive-to-create objects.
Method Signature:
public function singleton(string $name, Closure $resolver)
Parameters:
$name- The class name or interface name to bind$resolver- A Closure that returns the instance
Examples:
// Bind database connection as singleton
$app->singleton(DatabaseConnection::class, function ($app) {
return new DatabaseConnection(
config('database.host'),
config('database.user'),
config('database.pass')
);
});
// Bind a logger service
$app->singleton(Logger::class, function ($app) {
return new FileLogger('/var/logs/app.log');
});
Bind Instance
Bind an existing object instance to the container.
Description:
The instance() method binds an already instantiated object to the container. Subsequent requests for this service will return the given instance. This is useful for binding the current request object or other runtime artifacts.
Method Signature:
public function instance(string $name, $instance)
Parameters:
$name- The class name or alias to bind$instance- The object instance to bind
Examples:
// Bind the current user context
$currentUser = new User(123);
$app->instance(User::class, $currentUser);
// Bind a pre-configured configuration object
$config = new Configuration(['debug' => true]);
$app->instance('config', $config);
Resolving Services
Methods to retrieve instances from the container.
Make Instance
Resolve a class definition from the container.
Description:
The make() method resolves the given type from the container. If the type is not bound, the container will attempt to resolve it using reflection and automatically inject its dependencies. You can also pass parameters to override constructor dependencies.
Method Signature:
public function make(string $name, array $parameters = [])
Parameters:
$name- The class name or alias to resolve$parameters- (Optional) Associative array of parameters to override dependencies
Examples:
// Resolve a service
$paymentGateway = $app->make(PaymentGatewayInterface::class);
// Resolve with parameters
$order = $app->make(Order::class, ['id' => 123]);
// Resolve a controller automatically injecting dependencies
$controller = $app->make(ProductController::class);
Check Existence
Check if a class or alias exists in the container.
Description:
The has() method determines if a given service or alias is bound in the container, is a singleton instance, or is an existing class that can be autoloaded.
Method Signature:
public function has(string $name): bool
Parameters:
$name- The class name or alias to check
Examples:
if ($app->has(PaymentGatewayInterface::class)) {
// Service is available
}
if ($app->has('config')) {
// Config alias is bound
}
Aliasing and Tagging
Organize and group services.
Alias Service
Create an alias for a service.
Description:
The alias() method allows you to define a short string alias for a class name. This is often used to map short names like db or auth to their fully qualified class names.
Method Signature:
public function alias(string $alias, string $abstract)
Parameters:
$alias- The short alias name$abstract- The fully qualified class name it points to
Examples:
// Alias 'db' to DatabaseConnection class
$app->alias('db', DatabaseConnection::class);
// Resolve using alias
$db = $app->make('db');
// Alias interface to implementation
$app->alias('payment', StripePaymentGateway::class);
Tag Services
Tag multiple services for grouped resolution.
Description:
The tag() method assigns a tag to one or more services. This allows you to group related services (like event listeners, or report providers) and retrieve them all at once.
Method Signature:
public function tag(array $services, string $tag)
Parameters:
$services- Array of service class names$tag- The tag name to assign
Examples:
// Tag event listeners
$app->tag([
UserRegisteredListener::class,
WelcomeEmailListener::class,
], 'user.events');
// Tag report generators
$app->tag([
SalesReport::class,
InventoryReport::class,
], 'reports');
Resolve Tagged Services
Get all services with a given tag.
Description:
The tagged() method resolves all services that have been assigned the specified tag. It returns an array of instantiated objects.
Method Signature:
public function tagged(string $tag): array
Parameters:
$tag- The tag name to resolve
Examples:
// Get all event listeners
$listeners = $app->tagged('user.events');
foreach ($listeners as $listener) {
$listener->handle($event);
}
// Get all reports and generate them
$reports = $app->tagged('reports');
foreach ($reports as $report) {
$report->generate();
}
Container Management
Static methods for managing the container instance.
Get Container Instance
Get the singleton instance of the container.
Description:
The get_instance() static method returns the globally available singleton instance of the Container. This is useful when you need to access the container from a static context or inside a function where it's not injected.
Method Signature:
public static function get_instance(): self
Examples:
$app = Container::get_instance();
$app->make(SomeService::class);
Flush Container
Flush all bindings and instances.
Description:
The flush() method clears all bindings, resolved instances, aliases, and tags from the container. This is primarily used in testing to reset the container state between tests.
Method Signature:
public function flush()
Examples:
// Reset container state
$app->flush();