Closed
Description
Description
Use attributes to have autowiring between ServiceLocator and tagged services, by key that can be either FQCN (default) or allow users to define it. Upgrade of implementation: #29203
Example of FQCN index, along with psalm annotation use:
class MyService
{
public function __construct(
#[Tagged(name: 'form.type')] private ServiceLocator $tagged
) {}
/**
* @param class-string<FormTypeInterface> $className
*/
public function get(string $className): FormTypeInterface
{
return $this->tagged->get($className);
}
}
$formType = $myService->get(EntityType::class);
If users want different index (like #29203), optional parameter would be the name of static method used:
interface ExporterInterface
{
public static function getName(): string;
}
class CSVExporter implements ExporterInterface
{
public static function getName(): string
{
return 'csv_exporter';
}
}
class MyService
{
public function __construct(
#[Tagged(name: 'app.exporter', indexMethod: 'getName')] private ServiceLocator $tagged
) {}
public function get(string $name): ExporterInterface
{
return $this->tagged->get($name);
}
}
$exporter = $myService->get('csv_exporter'); // this would be instance of CSVExporter
If of any relevance, stub for ServiceLocator can be this:
/**
* @template T
*/
class ServiceLocator
{
/** @return T */
public function get($id){}
}