Skip to main content

Deferred Resolution

Overview

Deferred resolution delays the instantiation of a service until it is actually requested. By postponing service creation during the boot process, deferred resolution improves performance and reduces memory consumption by ensuring that only the services required for a particular request are constructed.


How Deferred Resolution Works

Deferred resolution is typically implemented using a service provider mechanism. When a service provider is marked as deferred (e.g., by setting its defer flag to true), its registration logic is delayed until one of its provided services is requested. This means that while the provider is registered with the container, its services are not instantiated during the initial boot process. Instead, they remain dormant until needed, ensuring that dependencies are resolved just in time.


Key Concepts

Deferred Service Provider:

A provider (such as a lazy service provider) marked as deferred does not immediately register its services. Instead, it waits until one of its services is explicitly requested before executing its registration logic.

Registration and Boot Process:

The container collects all service providers during registration. During boot, it processes non-deferred providers immediately, while those marked as deferred are held back. When a deferred service is requested, the container triggers the provider’s registration, instantiating the service on demand.

On-Demand Instantiation:

When you request a deferred service using $container->get(Service::class), the container checks for any associated deferred provider. If found, the provider’s registration logic runs at that moment, and the service is instantiated, ensuring that its dependencies are resolved at the time of need.


Code Example: Deferred Service Loading

$container = new Application();

// Instantiate the lazy service provider and mark it as deferred.
$provider = new LazyServiceProvider();
$provider->defer = true;

// Register the provider with the container and boot the application.
$container->registerProvider($provider);
$container->boot();

// The service LazyService is not instantiated until it is explicitly requested.
$lazyService = $container->get(LazyService::class);

In this example:

  • A lazy service provider is created and marked as deferred.
  • The provider is registered, but its services are not instantiated during the boot process.
  • When LazyService::class is requested, the container triggers the provider’s registration logic, instantiating the service on demand.

Summary

Deferred resolution is a key feature that optimizes resource usage by delaying the creation of services until they are needed. By using deferred service providers, the DomainFlow Container ensures a faster boot process and efficient memory usage, making your application more performant and scalable.