Skip to content

Исключение элементов из коллекции ​

Коллекции могу исключать элементы. Исключить из коллекции можно по идентификатору контейнера [1] элемента коллекции или вызывающий PHP-класс, т.е. самого себя.

Исключение из коллекции по идентификатору контейнера ​

Для исключения элементов из коллекции используйте параметр $containerIdExclude в хелпер функции diTaggedAs() и атрибуте \Kaspi\DiContainer\Attributes\TaggedAs.

Параметр $containerIdExclude может содержать идентификаторы контейнера [1:1] исключаемых из внедряемой коллекции.

Пример исключения из коллекции элементов ​

PHP классы:

php
<?php
declare(strict_types=1);

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

namespace App\Service;

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

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

namespace App\Service;

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

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

namespace App\Service;

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

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

namespace App\Service;

final class Qux
{
    // …
}

PHP-классы \App\Service\Bar, \App\Service\Baz, \App\Service\Qux будут отмечены тегом 'tags.internal_service'.

В параметр $services PHP класса \App\Service\Foo необходимо внедрить коллекцию элементов отмеченных тегом 'tags.internal_service', но исключить из коллекции элемент с идентификатором контейнера 'App\Services\Baz', т.е. сервис получаемый через метод контейнера $container->get(App\Services\Baz::class).

Объявление в файлах конфигураций ​

В файле конфигураций services.php в параметре $containerIdExclude хелпер функции diTaggedAs() указать идентификатор 'App\Services\Baz' для исключения из коллекции.

В файле конфигураций tagged_services.php объявить тег 'tags.internal_service' для остальных PHP классов через метод bindTag().

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.php')
    ->build();

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

foreach ($foo->services as $service) {
    var_dump($service::class);
}
php
<?php
declare(strict_types=1);

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

use App\Services\{Foo, Bar, Baz, Qux};

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

return static function (): Generator {
    yield diAutowire(Foo::class)
        ->bindArguments(
            services: diTaggedAs(
                tag: 'tags.internal_service',
                containerIdExclude: [
                    Baz::class,
                ],
            )
        );
        
    yield diAutowire(Bar::class)
        ->bindTag('tags.internal_service');
        
    yield diAutowire(Baz::class)
        ->bindTag('tags.internal_service');
        
    yield diAutowire(Qux::class)
        ->bindTag('tags.internal_service');
};
php
<?php
declare(strict_types=1);

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

use App\Services\{Bar, Baz, Qux};

use function Kaspi\DiContainer\diAutowire;

return static function (): Generator {
    yield diAutowire(Bar::class)
        ->bindTag('tags.internal_service');
        
    yield diAutowire(Baz::class)
        ->bindTag('tags.internal_service');
        
    yield diAutowire(Qux::class)
        ->bindTag('tags.internal_service');
};

Выполните в терминале команду:

shell
php /app/src/container_build.php

Появится сообщение вида:

console
string(16) "App\Services\Bar"
string(16) "App\Services\Qux"
Объявление через атрибуты ​

В параметре $containerIdExclude атрибута \Kaspi\DiContainer\Attributes\TaggedAs указать идентификатор 'App\Services\Baz' для исключения из коллекции.

Объявление тега 'tags.internal_service' остальным PHP-классам через атрибут \Kaspi\DiContainer\Attributes\Tag.

php
<?php
declare(strict_types=1);

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

namespace App\Service;

use Kaspi\DiContainer\Attributes\TaggedAs;

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

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

namespace App\Service;

use Kaspi\DiContainer\Attributes\Tag;

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

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

namespace App\Service;

use Kaspi\DiContainer\Attributes\Tag;

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

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

namespace App\Service;

use Kaspi\DiContainer\Attributes\Tag;

#[Tag('tags.internal_service')]
final class Qux
{
    // …
}
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);

foreach ($foo->services as $service) {
    var_dump($service::class);
}

Выполните в терминале команду:

shell
php /app/src/container_build.php

Появится сообщение вида:

console
string(16) "App\Services\Bar"
string(16) "App\Services\Qux"

Исключение вызывающего класса ​

В коллекции элементов может содержаться PHP-класс внедряющий эту же коллекцию. Для исключения такого поведения обратите внимание на параметр $selfExclude в хелпер функции diTaggedAs() и атрибуте \Kaspi\DiContainer\Attributes\TaggedAs. По умолчанию значение этого параметра true.

Если вызывающий PHP-класс должен быть в коллекции, то необходимо указать в параметр $selfExclude значение false.

php
<?php
declare(strict_types=1);

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

use App\Services\ClassTaggedAs;

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

return static function (): Generator {
    yield diAutowire(ClassTaggedAs::class)
        ->bindTag('tags.foo')
        ->bindArguments(
            items: diTaggedAs(
                'tags.foo',
                selfExclude: false,
            )
        );
};
php
<?php
declare(strict_types=1);

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

namespace App\Services;

use Kaspi\DiContainer\Attributes\{Tag, TaggedAs}; 

#[Tag('tags.foo')]
final class ClassTaggedAs
{
    public function __construct(
        #[TaggedAs(
            'tags.foo',
            selfExclude: false,
        )]
        public readonly iterable $items
    ) {}
}

  1. Идентификатор контейнера (Container ID) – это строковое имя (или имя класса/интерфейса), по которому сервис или объект зарегистрирован и запрашивается из контейнера через метод get(). ↩︎ ↩︎