Tags
Tags make it possible to expand the ways in which collections can be passed as parameters to methods and functions. Elements from a container that are marked with a tag of the same name are gathered into a collection.
Dependency injection is applicable to parameters of the following type:
iterable\Traversable\Iterator
\ArrayAccess\Psr\Container\ContainerInterfacearray(the argumentfalsemust be passed for the$isLazyparameter)\ArrayAccess & \Iterator & \Psr\Container\ContainerInterface
Any definition within a container can be marked with one or more tags. Each tag can contain metadata.
Объявить теги определения контейнера можно используя:
- Хелпер функции:
diAutowire(),diCallable(),diProxyClosure(),diValue(). - Атрибуты:
Autowire,Tag.
Dependency injection of a collection of elements into a parameter can be declared using:
- Helper functions:
diTaggedAs(). - Attributes:
TaggedAs.
IMPORTANT
PHP classes that have not been explicitly registered in the container will be ignored during tag-based lookups; therefore, you must ensure that these classes are added to the container using one of the following methods:
- importing PHP classes — via the
DiContainerBuilder::import()method. - using configuration files — via the
DiContainerBuilder::load()method.
Lazy Collection
An element of a lazy collection is initialized only at the moment it is actually accessed; this allows the creation of an object's dependencies to be deferred until the point they are truly needed, rather than any earlier.
A "lazy collection" is defined via the $isLazy parameter in the diTaggedAs() helper function or the TaggedAs attribute.
WARNING
A lazy collection cannot be applied to a parameter of type array. For parameters of type array, the $isLazy parameter must be set to false.
Identifier of an item in a collection
By default, an injected collection uses the container ID[1] of each element as its identifier.
This behavior can be modified using the $useKeys, $key, and $keyDefaultMethod parameters — available via the diTaggedAs() helper function or the TaggedAs attribute.
Element identifiers within a collection can be arbitrary strings or integers.
For more information, see the documentation section on "Collection Element Identifiers".
Section Contents
- 🐘 Declaring a tag in configuration files.
- #️⃣ Declaring a tag via an attribute.
- 📑 PHP interface as a tag name.
- 🚫 Removing elements from a collection.
- ⬆️ Priority of collection elements.
- 🔑 Collection element identifiers.
A container ID is a string name (or a class/interface name) used to register a service or object within a container and to retrieve it via the
get()method. ↩︎