Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Autowire ServiceLocator with iterable of tagged services #39924

Copy link
Copy link
Closed
@zmitic

Description

@zmitic
Issue body actions

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){}
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.