Skip to main content

Container Tags

Overview

Tag management allows you to group related service bindings under a common tag. This feature is especially useful when you have multiple services that share a common purpose—such as logging, event handling, or middleware—and you want to retrieve or process them as a group.


Tagging Services

Using the tag() Method

The tag() method accepts a tag name and an array of service identifiers. This association lets you later fetch all services tagged with that name. Internally, tags are stored in an associative array where the keys are tag names and the values are lists of service identifiers.

$container = new Container();

// Tag both logger implementations under the "logger" tag.
$container->tag('logger', [
FileLogger::class,
DatabaseLogger::class,
]);

Retrieving Tagged Services

Once services have been tagged, you can use getByTag() to retrieve them. This method returns an associative array where the keys are the service identifiers and the values are the resolved instances. If a tagged service is not found (for example, if it was removed or not bound), the method skips it gracefully without halting the retrieval process.

$loggers = $container->getByTag('logger');

foreach ($loggers as $serviceId => $logger) {
// Each $logger is an instance of its respective class.
$logger->log("This is a test message from {$serviceId}");
}

Benefits of Tag Management

  • Organization:
    Easily group services with similar roles.

  • Batch Operations:
    Retrieve all services in a tag group for batch processing.

  • Flexibility:
    Change, extend, or dynamically update the group without modifying each service individually.


Advanced Use-Cases

  • Dynamic Tagging:
    In more complex scenarios, services can be tagged dynamically during runtime to reflect changing application states or configurations.

  • PSR-11 Compatibility:
    Tag management integrates smoothly with containers adhering to the PSR-11 standard, allowing consistent retrieval and manipulation of tagged services.

  • Error Handling:
    The design of getByTag() ensures that if one or more services in a tag group are missing, the overall retrieval process continues without interruption.


Summary

Tag management is an essential feature for organizing and processing groups of related services. It enables you to quickly retrieve and manipulate sets of services that share a common function, simplifying maintenance and enhancing modularity.

By grouping services under tags and retrieving them as needed, you can perform batch operations, monitor related components, or dynamically adjust behavior based on the available services. This approach not only helps maintain a clean and modular architecture but also supports robust error handling and dynamic configuration in line with PSR-11 principles.