Skip to content

Add #[AsAlias] to allow defining service aliases using attributes #49361

@nicolas-grekas

Description

@nicolas-grekas

This has already been asked for in #41188 and #47323, and tentatively implemented in #41207 then #49198. We also have #48523 on the topic, which tries the reverse side approach of adding the attribute on the source side of the alias (the interface).

I realize that the intuitive side is to add the attribute on the target side of the alias (the service implementation).

Both implementations in #41207 and #49198 try so solve this with a compiler pass. I think this is not the correct approach, therefor this issue to describe what could be an acceptable approach.

Using compiler passes to create the aliases opens the possibility of collision, with little control over them. This would trivially happen if two services define a tag (possibly derived from an attribute) for the same alias.

To work around this issue, I think we should register such aliases during auto-discovery. That is, in FileLoader::registerClasses(). This method already auto-registers aliases for singly-implemented interfaces. Looking for #[AsAlias] there would resolve the conflicts in two steps:

  • if conflicting aliases are discovered in the same call to FileLoader::registerClasses(), a LogicException should be thrown
  • otherwise, regular service registration order would apply: the latest loaded config wins over the previous

As a side effect, this would mean that if a service is explicitly registered, then its AsAlias attribute would be ignored. I think this wouldn't be an issue since when you write a service explicitly, it's quite natural to also register it as an alias when needed. This would also give the most flexibility since this would make AsAlias easy to ignore if needed.

Help Wanted.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DependencyInjectionHelp wantedIssues and PRs which are looking for volunteers to complete them.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions