thephpleague / container

Small but powerful dependency injection container

Home Page:http://container.thephpleague.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Possible to use tags in Service Providers?

Tabrisrp opened this issue · comments

Hello 👋🏼 ,

While migrating from v2 to v3, I'm trying to use the new tagged definition system to get an array of specific services to loop over.

What is failing currently is that the tag added to services inside a service provider is not recognized by the container. An example with the tag subscriber:

$this->container->get( 'subscriber' );

generates Fatal error: Uncaught Exception: Alias (subscriber) is not being managed by the container or delegates

If I add the tag to a service registered outside of a service provider, the same method call returns the expected array.

Is this the expected behaviour, and tags can't be used in service providers, or am I missing something?

The problem here is that the container doesn't know where to find the tag.

Are all definitions for that tag in the same service provider? If so, add the tag name to 'provides' and it will resolve it correctly.

If the definitions are spread across multiple service providers, that may not work as expected, so I'd suggest implementing the bootable service provider for those, and moving those particular definitions to the boot method.

I will give this a bit more attention when I have time as it's made me see the issue with spreading tagged definitions across multiple service providers.

Hope this helps and I will keep you updated.

Thank you for the fast answer!

The definitions are indeed spread into multiple service providers, as each service has multiple definitions, including one or more subscriber in the way the app is built right now.

I'm going to take a look at using the bootable service provider for the tagged definitions, this could be a good workaround for now.

The problem with them being spread, is that service providers are lazily loaded and the container determines what to register based on the alias requested... which works great in most cases, but, once it finds a service provider that 'provides' the requested alias, it stops at that one. But that obviously becomes a problem if it's a tag and there are more definitions in service providers that it won't reach.

This is something I'd not thought of before so thanks for the report, I'll solve it the as soon as I can.

The boot method of a bootable service provider is eagerly loaded, so that will solve your problem and you won't need to add the tag to 'provides', it's not necessarily a workaround as such, but being able to lazy load is obviously better.