Skip to content

[DependencyInjection] PHP attribute for service aliases #47323

@SVillette

Description

@SVillette

Description

Since version 6.1 it is possible to exclude a service from a TaggedIterator (Living on the edge blog post).

Unfortunately, it is not possible to add an alias with a PHP attribute. This is the only missing feature needed to avoid writing configuration in YAML.

I asked about this feature on Slack and @wouterj told me that attributes for DI config is not aimed to be used for creating services.
However in this another blog post, @nicolas-grekas said that PR are welcome for this feature. So that's why I opened this issue.

Example

My use case is the following:

classDiagram
HandlerInterface <|-- HandlerA : implements
HandlerInterface <|-- HandlerB : implements
HandlerInterface <|-- CompositeHandler : implements
CompositeHandler : -iterable~HandlerInterface~ handlers
class HandlerInterface {
    <<interface>>
    +handle() void
}
class HandlerA {
    +handle() void
}
class HandlerB {
    +handle() void
}
class CompositeHandler {
    +handle() void
}
Loading
#[AutoconfigureTag(name: 'app.handler')]
interface HandlerInterface {
    public function handle(): void;
}

class CompositeHandler implements HandlerInterface {

    public function __construct(
        #[TaggedIterator(tag: 'app.handler', exclude: self::class)],
        private iterable $handlers
    ) {
    }

    public function handle(): void {
        foreach ($this->handlers as $handler) {
            $handler->handle();
        }
    }
}

As I need to inject HandlerInterface into another service, I will write the following YAML configuration to create an alias between the HandlerInterface and CompositeHandler:

services:
    app.handler:
        class: CompositeHandler
        
    HandlerInterface: '@app.handler'

From my point of view, define the alias with an attribute would simplify the configuration for this kind of cases.

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