-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Description
Description
Hey,
It would be awesome if we could enforce indexes to be unique for tagged service locators when using index method.
The issue with the current behaviour is that if I register another service, and its static method that is responsible for returning the (expeced to be unique) key returns a key that already exists, the existing service in the locator is replaced.
This may not always be the desired behavour. Sometimes you may want to be able to do so and could come in handy, but other times you may need to enforce uniqueness and disallow registering the same thing twice and consider it a mistake.
My suggestion is to add another config option, such as unique="true"
(in XML), and upon a duplicate, a RuntimeException
would be thrown, preventing you from running anything in the project until fixed.
Example
Before
<service id="App\HandlerCollection">
<argument type="tagged_locator" tag="app.handler" index-by="key"
default-index-method="myOwnMethodName"/>
</service>
No error, another app.handler
may replace an existing one.
After
<service id="App\HandlerCollection">
<argument type="tagged_locator" tag="app.handler" index-by="key"
default-index-method="myOwnMethodName" unique="true"/>
</service>
A RuntimeError is thrown, with a message such as "Service for index %s already exists in this locator as %s. Adding %s with the same key is impossible for tagged locators with unique indexes."
1 - index value
2 - existing service id
3 - next service id to be added to the locator
I assume (didn't do the research yet) that tagged locators are computed in a compiler pass, so throwing the exception there would make sense? This is how I currently solve this.
This allows you to know immediately when something isn't quite right in the project during development, as soon as you make a mistake, rather than spending hours in debugging and figuring out why your unique collection is misbehaving.
WDYT?