-
-
Save NicolasBadey/82c05e17bf2c46bac389cbda8286eab0 to your computer and use it in GitHub Desktop.
Symfony : Inject all class implementing a specific interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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('...') | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace App\Calculator; | |
interface CalculatorInterface | |
{ | |
public function support(string $name): boolean; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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