Symfony: Automatically inject a stack of plugins into a service

<?php

namespace
App;
use App\Text;
use App\Filter\FirstFilter;
use App\Filter\SecondFilter;
use App\Filter\ThirdFilter;

class FilterExecutor
{
/**
*
@var \App\Filter\FilterInterface[]|array
*/
protected $filters = [];

/**
*
@return void
*/
public function applyFilters(Text $text): void
{
$this->loadFilters();

foreach($this->filters as $filter) {
$filter->execute($text);
}
}

/**
*
@return void
*/
protected function loadFilters(): void
{
$this->filters = [
new FirstFilter(),
new SecondFilter(),
new ThirdFilter(),
];
}
}
<?php

namespace
App;
use App\Text;

class FilterExecutor
{
/**
*
@var \App\Filter\FilterInterface[]|array
*/
protected $filters = [];

/**
* Services with FilterInterface will be injected automatically
*
*
@param \App\Filter\FilterInterface[]|array $filters
*/
public function __construct(array $filters)
{
$this->filters = $filters;
}

/**
*
@return void
*/
public function applyFilters(Text $text): void
{
foreach($this->filters as $filter) {
$filter->execute($text);
}
}
}
_instanceof:
# tagging all services that implement FilterInterface
App\Filter\FilterInterface:
tags: ['app.text_filter']
App\FilterExecutor:
class: App\FilterExecutor
arguments:
# add services that have "app.text_filter" tag as argument
— !tagged app.text_filter

--

--

--

Web Developer in Berlin — www.kcmueller.de

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KC Müller

KC Müller

Web Developer in Berlin — www.kcmueller.de

More from Medium

How to solve PHP Laravel arrow function error in VS code — “ syntax error, unexpected ‘=>’…

VS code throwing arrow function error in PHP Laravel— “syntax error, unexpected ‘=>’ (T_DOUBLE_ARROW), expecting ‘)’”

How to enable PCNTL in Apache

What Are SOLID Principles?

NPM commands