@florianm__
Florian-Merle
AKAWAKA
Découvrir ce que cache l'injection de dépendances 🔗
Services,
Paramètres,
Tags,
Etc.
Pour le défi technique 🏋️
namespace Psr\Container;
/**
* Describes the interface of a container that exposes methods to read its entries.
*/
interface ContainerInterface
{
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id Identifier of the entry to look for.
*
* @return mixed Entry.
*/
public function get($id);
/**
* Returns true if the container can return an entry for the given identifier.
* Returns false otherwise.
*
* @param string $id Identifier of the entry to look for.
*
* @return bool
*/
public function has($id);
}
ContainerBuilder.php 👷
config.yaml 🔧
Container.php 📦
::buildcontainer(): Container
Implemente PSR-11
final class ContainerBuilder
{
public function buildContainer(): Container
{
$config = \yaml_parse_file('config.yaml');
return new Container(
config: $config,
serviceIds: $this->resolveServiceIds($config),
);
}
/** @param string[] $config */
private function resolveServiceIds(array $config): array
{
$serviceConfigList = $config['services'] ?? [];
return array_keys($serviceConfigList);
}
}
services:
App\SmsSender: ~
App\Mailer: ~
app.weather_listener:
class: App\Listener\Weather
parameters:
notifier: '@App\Mailer'
final class Container implements ContainerInterface
{
public function get(string $id): mixed
{
if (false === $this->has($id)) {
throw new NotFoundException();
}
if (false === array_key_exists($id, $this->services)) {
$this->services[$id] = $this->buildInstance($id);
}
return $this->services[$id];
}
}
public function has(string $id): bool
{
return in_array($id, $this->serviceIds);
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
private function buildInstance(string $id): mixed
{
$serviceConfig = $this->config['services'][$id] ?? [];
$reflector = new \ReflectionClass($serviceConfig['class'] ?? $id);
if (!$reflector->isInstantiable()) {
throw new ContainerException("Service $id is not instantiable");
}
$constructor = $reflector->getConstructor();
if (null === $constructor || empty($constructor->getParameters())) {
$instance = $reflector->newInstance();
} else {
$parameters = $this->resolveDependencies($constructor->getParameters(), $serviceConfig);
$instance = $reflector->newInstanceArgs($parameters);
}
return $instance;
}
}
services:
App\Mailer: ~
App\Listener\Weather:
parameters:
notifier: '@App\Mailer'
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
{
$dependencies = [];
foreach ($constructorParameterList as $constructorParameter) {
$dependencies[] = $this->resolveDependency($constructorParameter, $serviceConfig);
}
return $dependencies;
}
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()];
// To-do: services, parameters, etc.
return $value;
}
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()];
// service
if (str_starts_with($value, '@')) {
return $this->get(substr($value, 1));
}
return $value;
}
}
services:
App\Mailer: ~
App\Listener\Weather:
parameters:
notifier: '@App\Mailer'
class Mailer implements NotifierInterface
{
}
class WeatherListener
{
public function __construct(private NotifierInterface $notifier) {}
}
services:
App\Controller\RoutePlannerController:
parameters:
- '@App\Provider\WeatherProvider'
- '@App\PointOfInterestFinder'
- '@App\Repository\RouteRepository'
App\Provider\WeatherProvider:
parameters:
apiKey: '%weather_provider.api_key%'
App\PointOfInterestFinder: ~
App\Repository\RouteRepository:
parameters:
entityManager: '@App\EntityManager'
App\EntityManager: ~
$ tree src/
src/
├── Controller
│ ├── RoutePlannerController.php
├── Provider
│ ├── WeatherProvider.php
├── Repository
│ ├── RouteRepository.php
├── EntityManager.php
├── PointOfInterestFinder.php
└── Kernel.php
3 directories, 6 files
Container
Services
services:
App\Controller\RoutePlannerController:
parameters:
- '@App\Provider\WeatherProvider'
- '@App\PointOfInterestFinder'
- '@App\Repository\RouteRepository'
App\Provider\WeatherProvider:
parameters:
apiKey: '%weather_provider.api_key%'
App\PointOfInterestFinder: ~
App\Repository\RouteRepository:
parameters:
entityManager: '@App\EntityManager'
App\EntityManager: ~
autowiring:
App\:
resource: '../src/'
exclude:
- '../src/Command/'
- '../src/Entity/'
- '../src/Kernel.php'
services:
App\Provider\WeatherProvider:
parameters:
apiKey: '%weather_provider.api_key%'
Trouver les services à "autowire"
Autowire les dépendances
has(id) ?
final class ContainerBuilder
{
public function buildContainer(): Container
{
$config = \yaml_parse_file('config.yaml');
return new Container(
config: $config,
serviceIds: $this->resolveServiceIds($config),
);
}
/**
* @param string[] $config
*/
private function resolveServiceIds(array $config): array
{
return array_keys($config['services']);
}
}
final class ContainerBuilder
{
public function buildContainer(): Container
{
$config = \yaml_parse_file('config.yaml');
return new Container(
config: $config,
serviceIds: $this->resolveServiceIds($config),
);
}
/**
* @param string[] $config
*/
private function resolveServiceIds(array $config): array
{
$ids = [
...array_keys($config['services']),
...ContainerBuilderHelper::findAutowirableServiceIds($config),
];
return array_unique($ids);
}
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()] ?? null;
// service
if (str_starts_with($value, '@')) {
return $this->get(substr($value, 1));
}
return $value;
}
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()] ?? null;
if (null === $value) {
try {
return $this->get($constructorParameter->getType()->__toString());
} catch(NotFoundExceptionInterface) {
throw new ContainerException('Cannot autowire parameter');
}
}
// service
if (str_starts_with($value, '@')) {
return $this->get(substr($value, 1));
}
return $value;
}
}
services:
App\Controller\RoutePlannerController:
parameters:
- '@App\Provider\WeatherProvider'
- '@App\PointOfInterestFinder'
- '@App\Repository\RouteRepository'
App\Provider\WeatherProvider:
parameters:
apiKey: '%weather_provider.api_key%'
App\PointOfInterestFinder: ~
App\Repository\RouteRepository:
parameters:
entityManager: '@App\EntityManager'
App\EntityManager: ~
autowiring:
App\:
resource: '../src/'
exclude:
- '../src/Command/'
- '../src/Entity/'
- '../src/Kernel.php'
services:
App\Provider\WeatherProvider:
parameters:
apiKey: '%weather_provider.api_key%'
final class PointOfInterestHandler
{
public function __construct(
private HotelHandler $hotelHandler,
private FuelHandler $fuelHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Hotel) {
return $this->hotelHandler->handle($pointOfInterest);
}
if ($pointOfInterest instanceof Fuel) {
return $this->fuelHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
final class PointOfInterestHandler
{
public function __construct(
private HotelHandler $hotelHandler,
private FuelHandler $fuelHandler,
private FoodHandler $foodHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Hotel) {
return $this->hotelHandler->handle($pointOfInterest);
}
if ($pointOfInterest instanceof Fuel) {
return $this->fuelHandler->handle($pointOfInterest);
}
if ($pointOfInterest instanceof Food) {
return $this->foodHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
final class PointOfInterestHandler
{
/** @param iterable<HandlerInterface> $handlers */
public function __construct(
private iterable $handlers,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
foreach ($this->handlers as $handler) {
if ($handler->can($pointOfInterest)) {
return $handler->handle($pointOfInterest);
}
}
throw new \LogicException("No handler found");
}
}
interface HandlerInterface
{
public function can(PointOfInterest $pointOfInterest): bool;
public function handle(PointOfInterest $pointOfInterest): mixed;
}
services:
App\PointOfInterestHandler:
parameters:
handlers: '!tagged_iterator point_of_interest_handler'
App\HotelHandler:
tags:
- { name: 'point_of_interest_handler' }
App\FuelHandler:
tags:
- { name: 'point_of_interest_handler' }
App\FoodHandler:
tags:
- { name: 'point_of_interest_handler' }
🚩
🚩
🚩
🪣
🚩
🚩
🚩
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()];
// service
if (str_starts_with($value, '@')) {
return $this->get(substr($value, 1));
}
return $value;
}
}
services:
App\PointOfInterestHandler:
parameters:
handlers: '!tagged_iterator point_of_interest_handler'
// tagged iterator
if (str_starts_with($value, '!tagged_iterator ')) {
$tag = substr($value, 17);
// find service with a specific tag
$taggedServiceListConfig = ContainerHelper::findTaggedServices(
$tag,
$this->config['services']
);
$taggedServices = [];
foreach ($taggedServiceListConfig as $id => $taggedServiceConfig) {
$taggedServices[] = $this->get($id);
}
return $taggedServices;
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()];
// service
if (str_starts_with($value, '@')) {
return $this->get(substr($value, 1));
}
return $value;
}
}
services:
App\PointOfInterestHandler:
parameters:
handlers: '!tagged_iterator point_of_interest_handler'
final class PointOfInterestHandler
{
public function __construct(
private HotelHandler $hotelHandler,
private FuelHandler $fuelHandler,
private FoodHandler $foodHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Hotel) {
return $this->hotelHandler->handle($pointOfInterest);
}
if ($pointOfInterest instanceof Fuel) {
return $this->fuelHandler->handle($pointOfInterest);
}
if ($pointOfInterest instanceof Food) {
return $this->foodHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
final class HotelHandler implements HandlerInterface
{
public function __construct(
private ?HandlerInterface $nextHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Hotel) {
// do stuff
return 'hotel';
}
if ($this->nextHandler) {
return $this->nextHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
final class HotelHandler implements HandlerInterface
{
public function __construct(
private ?HandlerInterface $nextHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Hotel) {
// do stuff
return 'hotel';
}
if ($this->nextHandler) {
return $this->nextHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
final class FuelHandler implements HandlerInterface
{
public function __construct(
private ?HandlerInterface $nextHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Fuel) {
// do stuff
return 'fuel';
}
if ($this->nextHandler) {
return $this->nextHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
final class FoodHandler implements HandlerInterface
{
public function __construct(
private ?HandlerInterface $nextHandler,
) {
}
public function handle(PointOfInterest $pointOfInterest): mixed
{
if ($pointOfInterest instanceof Food) {
// do stuff
return 'food';
}
if ($this->nextHandler) {
return $this->nextHandler->handle($pointOfInterest);
}
throw new \LogicException("No handler found");
}
}
HotelHandler
FuelHandler
FoodHandler
HandlerInterface
services:
point_of_interest_handler:
class: App\HotelHandler
App\FuelHandler:
decorates: point_of_interest_handler
parameters:
nextHandler: '@.inner'
App\FoodHandler:
decorates: point_of_interest_handler
parameters:
nextHandler: '@.inner'
HotelHandler
FuelHandler
FoodHandler
point_of_interest_handler
final class Container implements ContainerInterface
{
public function get(string $id): mixed
{
if (false === $this->has($id)) {
throw new NotFoundException();
}
if (false === array_key_exists($id, $this->services)) {
$this->services[$id] = $this->buildInstance($id);
}
return $this->services[$id];
}
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
// private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
}
services:
point_of_interest_handler:
class: App\HotelHandler
App\FuelHandler:
decorates: point_of_interest_handler
parameters:
nextHandler: '@.inner'
App\FoodHandler:
decorates: point_of_interest_handler
parameters:
nextHandler: '@.inner'
final class Container implements ContainerInterface
{
public function get(string $id): mixed
{
if (false === $this->has($id)) {
throw new NotFoundException();
}
if (false === array_key_exists($id, $this->services)) {
$this->services[$id] = $this->buildInstance(
ContainerHelper::getMainId($id, $this->serviceIds, $this->config),
);
}
return $this->services[$id];
}
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
// private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
}
// decoration
if (str_starts_with($value, '@.inner')) {
$stack = ContainerHelper::getDecorationStack($id, $this->serviceIds, $this->config);
$currentPosition = array_search($id, array_keys($stack));
return $this->buildInstance(array_keys($stack)[$currentPosition - 1]);
}
final class Container implements ContainerInterface
{
// public function get(string $id): mixed
// private function buildInstance(string $id): mixed
// private function resolveDependencies(array $constructorParameterList, array $serviceConfig): array
private function resolveDependency(ReflectionParameter $constructorParameter, array $serviceConfig): mixed
{
$value = $serviceConfig['parameters'][$constructorParameter->getName()];
// service
if (str_starts_with($value, '@')) {
return $this->get(substr($value, 1));
}
return $value;
}
}
composer require cmfcmf/openweathermap-php-api
<?php
use Cmfcmf\OpenWeatherMap;
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
use Http\Factory\Guzzle\RequestFactory;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;
$httpRequestFactory = new RequestFactory();
$httpClient = GuzzleAdapter::createWithConfig([]);
$owm = new OpenWeatherMap('YOUR-API-KEY', $httpClient, $httpRequestFactory);
$weather = $owm->getWeather('Berne', 'metric', 'ch');
echo $weather->temperature;
services:
weather.client:
factory: ['@App\Weather\ClientFactory', 'create']
services:
weather.client:
factory: ['@App\Weather\ClientFactory', 'create']
final class Container implements ContainerInterface
{
// ...
private function buildInstance(string $id): mixed
{
$serviceConfig = $this->config['services'][$id] ?? [];
$reflector = new \ReflectionClass($serviceConfig['class'] ?? $id);
if (!$reflector->isInstantiable()) {
throw new ContainerException("Service $id is not instantiable");
}
$constructor = $reflector->getConstructor();
if (null === $constructor || empty($constructor->getParameters())) {
$instance = $reflector->newInstance();
} else {
$parameters = $this->resolveDependencies($constructor->getParameters(), $serviceConfig);
$instance = $reflector->newInstanceArgs($parameters);
}
return $instance;
}
}
final class Container implements ContainerInterface
{
// ...
private function buildInstance(string $id): mixed
{
$serviceConfig = $this->config['services'][$id] ?? [];
$factoryConfig = $serviceConfig['factory'] ?? null;
if ($factoryConfig !== null) {
$factoryServiceId = substr($factoryConfig[0], 1);
$factoryMethod = $factoryConfig[1];
return $this->get($factoryServiceId)->$factoryMethod();
}
$reflector = new \ReflectionClass($serviceConfig['class'] ?? $id);
if (!$reflector->isInstantiable()) {
throw new ContainerException("Service $id is not instantiable");
}
$constructor = $reflector->getConstructor();
if (null === $constructor || empty($constructor->getParameters())) {
$instance = $reflector->newInstance();
} else {
$parameters = $this->resolveDependencies($constructor->getParameters(), $serviceConfig);
$instance = $reflector->newInstanceArgs($parameters);
}
return $instance;
}
}
services:
weather.client:
factory: ['@App\Weather\ClientFactory', 'create']
class ClientFactory
{
public function __construct(private string $apiKey) {}
pulbic function create(): OpenWeatherMap
{
return new OpenWeatherMap(
$this->apiKey,
GuzzleAdapter::createWithConfig([]),
new RequestFactory(),
);
}
}
services:
weather.client:
factory: ['@App\Weather\ClientFactory', 'create']
CustomContainer
Services
Container
Services
CustomContainer
Services
Container
Services
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}
use App\DependencyInjection\Container as CustomContainer;
use App\DependencyInjection\ContainerBuilder as CustomContainerBuilder;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
private CustomContainer $customContainer;
public function boot(): void
{
$containerBuilder = new CustomContainerBuilder();
$this->customContainer = $containerBuilder->buildContainer();
parent::boot();
}
}
class Kernel extends BaseKernel
{
use MicroKernelTrait;
private CustomContainer $customContainer;
// public function boot(): void
protected function initializeContainer(): void
{
parent::initializeContainer();
foreach ($this->customContainer->getIds() as $id) {
$this->container->set($id, $this->customContainer->get($id));
}
}
}
class Kernel extends BaseKernel
{
use MicroKernelTrait;
private CustomContainer $customContainer;
// public function boot(): void
// protected function initializeContainer(): void
protected function build(ContainerBuilder $container): void
{
$container->addCompilerPass(
new RegisterCustomServicesCompilerPass($this->customContainer)
);
}
}
class RegisterCustomServicesCompilerPass implements CompilerPassInterface
{
public function __construct(
private readonly CustomContainer $customContainer
) {
}
public function process(ContainerBuilder $container): void
{
foreach ($this->customContainer->getIds() as $id) {
$service = $this->customContainer->get($id);
$definition = new Definition(get_class($service));
$definition->setSynthetic(true);
$container->setDefinition($id, $definition);
}
}
}
Services
Paramètres
Tags
Compiler pass
Référence circulaire
Alias
Configurator
Factory
Lazy Services
Immutable-setter Injection
Service Closures
Decoration
Service locator
Non Shared Services
Synthetic services
Parent Services
Autowiring
SOLID 💪
Différents environnements 🎭
Optimisation 🚀
Configuration facilitée👌
Merci 🙏