Skip to content

Autowire ServiceLocator with iterable of tagged services #39924

@zmitic

Description

@zmitic

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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy