Chapter 7 of 15
Dependency Injection and Service Providers.
Compose the application explicitly in providers and consume services through constructor injection.
Registering services
A provider implements ServiceProviderInterface. In register(ContainerBuilderInterface $builder), it declares bindings, aliases, and tags; the current request is not available there.
app/Providers/AppServiceProvider.php
<?php
declare(strict_types=1);
use App\Services\ArticleRepository;
use App\Services\ArticleRepositoryInterface;
use Lemonade\Framework\Container\ContainerBuilderInterface;
use Lemonade\Framework\Core\ServiceProviderInterface;
final class AppServiceProvider implements ServiceProviderInterface
{
public function register(ContainerBuilderInterface $builder): void
{
$builder->scoped(ArticleRepository::class, ArticleRepository::class);
$builder->alias(ArticleRepositoryInterface::class, ArticleRepository::class);
}
}List the provider in app/Config/Providers.yaml. Bind interfaces to registered concrete services.
Service lifetimes
singleton() shares an instance in the root runtime, scoped() shares one in a Request, Command, or Job scope, and transient() creates a fresh instance for every resolution. Post-registration side effects belong in BootableServiceProviderInterface::boot().