Learn how to use dependency injection and the service container in Aeros
The service container is a powerful tool for managing class dependencies and performing dependency injection. It allows you to register services once and access them throughout your application.
Aeros provides a built-in service container that extends the Kernel class and implements the singleton pattern. The container manages your application’s services, resolves dependencies, and provides a clean way to access core components.
The register() method binds a service into the container:
app()->register('logger', \Aeros\Src\Classes\Logger::class);// Register with a callableapp()->register('config', function() { return new Config(['env' => 'production']);});
From ServiceContainer.php:194-216, the register method accepts:
A string class name - Automatically instantiates the class
A callable - Executes when the service is resolved
If you try to register a class that doesn’t exist, Aeros will throw an exception.
<?phpnamespace App\Providers;use Aeros\Src\Classes\ServiceProvider;class CustomServiceProvider extends ServiceProvider{ /** * Register service bindings */ public function register(): void { app()->register('custom', function() { return new CustomService(); }); } /** * Bootstrap services after registration */ public function boot(): void { // Perform actions after all services are registered app()->custom->initialize(); }}
Initializes the main AppServiceProvider and sets up core functionality:
public function bootApplication(): ServiceContainer{ if ($this->isAppBooted) { return $this; } (new \App\Providers\AppServiceProvider)->register(); $this->isAppBooted = true; return $this;}
Calls the register() method on all configured providers:
public function registerProviders(): ServiceContainer{ foreach ($this->getProviders() as $providerWithNamespace) { if ($this->isProvider($providerWithNamespace)) { (new $providerWithNamespace)->register(); } } return $this;}
Calls the boot() method on all registered providers:
public function bootProviders(): ServiceContainer{ foreach ($this->getProviders() as $providerWithNamespace) { if ($this->isProvider($providerWithNamespace)) { (new $providerWithNamespace)->boot(); } } return $this;}
The entire bootstrap process is orchestrated by the bootstrap() method (ServiceContainer.php:95-100):
public function bootstrap(): ServiceContainer{ return $this->bootApplication() ->registerProviders() ->bootProviders();}