Návod
Služby a providery
Registrácia služieb, binding rozhraní a explicitné skladanie aplikácie.
Registruj služby v AppServiceProvider
Kompozícia aplikácie patrí do App\Providers\AppServiceProvider. Pre zdieľané služby používaj singleton(), pre opakovane vytvárané služby set().
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Services\ArticleRepository;
use Lemonade\Framework\Container\ContainerInterface;
use Lemonade\Framework\Core\ServiceProviderInterface;
final class AppServiceProvider implements ServiceProviderInterface
{
public function register(ContainerInterface $container): void
{
$container->singleton(ArticleRepository::class, ArticleRepository::class);
}
}Závislosti odovzdávaj konštruktorom
Controllery aj služby majú deklarovať svoje závislosti v konštruktore. Dependency graph tak zostáva čitateľný a kód sa ľahšie testuje.
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Services\ArticleRepository;
use Lemonade\Framework\Core\AbstractController;
use Psr\Http\Message\ResponseInterface;
final class ArticleController extends AbstractController
{
public function __construct(
private readonly ArticleRepository $articles,
) {}
public function detail(int $id): ResponseInterface
{
return $this->json($this->articles->find($id));
}
}Rozhrania a typovaná konfigurácia
Rozhrania potrebujú explicitný binding. YAML konfiguráciu za behu používaj cez typované config objekty, nie cez náhodné volania getenv().
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Services\NewsletterSender;
use App\Services\NewsletterSenderInterface;
use Lemonade\Framework\Container\ContainerInterface;
use Lemonade\Framework\Core\ServiceProviderInterface;
final class AppServiceProvider implements ServiceProviderInterface
{
public function register(ContainerInterface $container): void
{
$container->singleton(NewsletterSenderInterface::class, NewsletterSender::class);
}
}