Skip to content

Instantly share code, notes, and snippets.

@NicolasBadey
Forked from takali/CalculatorHandler.php
Last active September 16, 2022 15:06
Show Gist options
  • Save NicolasBadey/82c05e17bf2c46bac389cbda8286eab0 to your computer and use it in GitHub Desktop.
Save NicolasBadey/82c05e17bf2c46bac389cbda8286eab0 to your computer and use it in GitHub Desktop.
Symfony : Inject all class implementing a specific interface
<?php
namespace App\Handler;
use App\Calculator\CalculatorInterface;
class CalculatorHandler
{
/**
* @var CalculatorInterface[]
*/
private $calculatorList = [];
public function __construct(iterable $calculatorList)
{
$this->calculatorList = $calculatorList;
}
public function __invoke(string $name) : CalculatorInterface
{
foreach ($this->calculatorList as &$calculator) {
if (true === $calculator->support($name)) {
return $calculator;
}
}
throw new \Exception('...')
}
}
namespace App\Calculator;
interface CalculatorInterface
{
public function support(string $name): boolean;
}
services:
App\Handler\CalculatorHandler:
arguments: [!tagged app.calculator]
_instanceof:
App\Calculator\CalculatorInterface:
tags: ['app.calculator']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment