Kapitola 7 z 15

Dependency Injection a Service Providers.

Skládejte aplikaci explicitně v providerech a služby používejte přes konstruktorové DI.

Registrace služeb

Provider implementuje ServiceProviderInterface. V register(ContainerBuilderInterface $builder) deklaruje bindingy, aliasy a tagy; aktuální request zde není dostupný.

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);
    }
}

Třídu provideru uveďte v app/Config/Providers.yaml. Rozhraní svažte s registrovanou konkrétní službou.

Životnost služeb

singleton() sdílí instanci v kořenovém runtime, scoped() jednu instanci v Request, Command nebo Job scope a transient() vytváří novou instanci při každém vyřešení. Side effects po registraci patří do BootableServiceProviderInterface::boot().

Podrobná technická dokumentace na GitHubu