Skip to content

Collection element identifiers ​

By default, a collection uses the container identifier[1] of each item as its element identifier, which allows you to access the items in the collection in any order.

You can assign custom identifiers to collection elements using tag metadata or PHP class methods:

WARNING

When accessing an element in a collection via its string identifier, an exception of type \Psr\Container\NotFoundExceptionInterface may be thrown if the element is not found.

IMPORTANT

The identifier method must be declared within a PHP class using the public and static modifiers. The method must return a string.

The method accepts two arguments, which are passed by the container:

  • string $tag – the tag name.
  • array $options – tag metadata.

These parameters can be used to define the logic for generating an identifier for a collection element.

Random access to collection elements ​

When injecting a collection via the diTaggedAs() helper function or the \Kaspi\DiContainer\Attributes\TaggedAs attribute, the $isLazy parameter defaults to true. This means that the injected object will be a lazy collection.

A lazy collection implements the following interfaces:

  • \Iterator
  • \Psr\Container\ContainerInterface
  • \ArrayAccess
  • \Countable

Implementing these interfaces enables:

  • Iterating over collection elements using the PHP foreach language construct.
  • Accessing elements by their identifier using PHP array-style syntax — e.g. $service['foo.name'].
  • Accessing elements via the get() and has() methods as defined in PSR-11.

Example of collection implementation ​

PHP classes:

php
<?php
declare(strict_types=1);

// file: /app/src/Services/Foo.php

namespace App\Services;

final class Foo
{
    public function __construct(
        public readonly iterable $services
    ) {}
}
php
<?php
declare(strict_types=1);

// file: /app/src/Services/Bar.php

namespace App\Services;

final class Bar
{
    // …
}
php
<?php
declare(strict_types=1);

// file: /app/src/Services/Baz.php

namespace App\Services;

final class Baz
{
    // …
}

It is necessary to inject a lazy collection into the $services constructor parameter of the PHP class \App\Services\Foo, with access to the collection elements via their container identifiers.

Declaration in configuration files ​

Configure the injection of a lazy collection of elements marked with the 'tags.internal' tag into the $services parameter of the PHP class \App\Services\Foo using the diTaggedAs() helper function within the services.php configuration file. To ensure that the container identifier for each element serves as its key in the collection, the $useKeys parameter of the helper function should be set to true (which is the default value).

In the tagged_services.php configuration file, assign the 'tags.internal' tag to the PHP classes that represent the elements of this collection by using the bindTag()[2] method.

php
<?php
declare(strict_types=1);

// file: /app/src/container_build.php

require_once __DIR__.'/../vendor/autoload.php';

use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Foo;

$container = (new DiContainerBuilder())
    ->load('/app/config/services.php')
    ->load('/app/config/tagged_services.php')
    ->build();

$foo = $container->get(Foo::class);

// accessing a collection element via methods `\Psr\Container\ContainerInterface`
$bar = $foo->services->get(Bar::class);

var_dump($bar::class);

// accessing a collection element via methods `\ArrayAccess`
$baz = $foo->services[Baz::class];

var_dump($baz::class);

// counting the number of elements in a collection via `\Countable`
var_dump(count($foo->services));
php
<?php
declare(strict_types=1);

// file: /app/config/services.php

use App\Services\Foo;

use function \Kaspi\DiContainer\{diAutowire, diTaggedAs};

return static function (): Generator {
    yield diAutowire(Foo::class)
        ->bindArguments(
            servies: diTaggedAs('tags.internal')
        );
};
php
<?php
declare(strict_types=1);

// file: /app/config/tagged_services.php

use App\Services\{Bar, Baz};

use function \Kaspi\DiContainer\diAutowire;

return static function (): Generator {
    yield diAutowire(Bar::class)
        ->bindTag('tags.internal');

    yield diAutowire(Baz::class)
        ->bindTag('tags.internal');
};

Run the following command in the terminal:

shell
php /app/src/container_build.php

A message like the following will appear:

console
string(16) "App\Services\Bar"
string(16) "App\Services\Baz"
int(2)

Declaration via attributes ​

Declare the injection of a collection of elements marked with the tag 'tags.internal' into the $services parameter of the PHP class \App\Services\Foo using the \Kaspi\DiContainer\Attributes\TaggedAs attribute. The container identifier for each element in the collection should serve as its key; this is achieved by setting the $useKeys attribute parameter to true (which is the default value).

We will assign the tag 'tags.internal' to PHP classes using the \Kaspi\DiContainer\Attributes\Tag attribute.

PHP classes:

php
<?php
declare(strict_types=1);

// file: /app/src/Services/Foo.php

namespace App\Services;

use Kaspi\DiContainer\Attributes\TaggedAs;

final class Foo
{
    public function __construct(
        #[TaggedAs('tags.internal')]
        public readonly iterable $services
    ) {}    
}
php
<?php
declare(strict_types=1);

// file: /app/src/Services/Bar.php

namespace App\Services;

use Kaspi\DiContainer\Attributes\Tag;

#[Tag('tags.internal')]
final class Bar
{
    // …
}
php
<?php
declare(strict_types=1);

// file: /app/src/Services/Baz.php

namespace App\Services;

use Kaspi\DiContainer\Attributes\Tag;

#[Tag('tags.internal')]
final class Baz
{
    // …
}
php
<?php
declare(strict_types=1);

// file: /app/src/container_build.php

require_once __DIR__.'/../vendor/autoload.php';

use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Foo;

$container = (new DiContainerBuilder())
    ->import(namespace: 'App\\', src: '/app/src')
    ->build();

$foo = $container->get(Foo::class);

// accessing a collection element via `\Psr\Container\ContainerInterface` methods
$bar = $foo->services->get(Bar::class);

var_dump($bar::class);

// accessing a collection element via `\ArrayAccess` methods
$baz = $foo->services[Baz::class];

var_dump($baz::class);

// counting the number of elements in the collection via `\Countable`
var_dump(count($foo->services));

Run the following command in the terminal:

shell
php /app/src/container_build.php

A message like the following will appear:

console
string(16) "App\Services\Bar"
string(16) "App\Services\Baz"
int(2)

  1. 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. ↩︎

  2. To specify tags, use the bindTag() method, which is available in helper functions: diAutowire(), diCallable(), diProxyClosure(), diValue(). ↩︎