Атрибут Autowire
Атрибут \Kaspi\DiContainer\Attributes\Autowire объявляет PHP-класс в контейнере, или внедряет зависимость в параметр метода.
Конфигурация атрибута:
\Attribute::TARGET_CLASS\Attribute::TARGET_PARAMETER\Attribute::IS_REPEATABLE
Сигнатура атрибута:
\Kaspi\DiContainer\Attributes\Autowire::__construct(
string $id = '',
?bool $isSingleton = null,
array $arguments = [],
array|\Kaspi\DiContainer\Attributes\Tag|null $tags = null,
?array $setups = null,
callable|false|string $resetter = false,
bool $isLazy = false,
)Параметры:
$id– идентификатор контейнера [1], или пустая строка.$isSingleton– возвращать один и тот же объект (паттерн singleton). Если значениеnull, то значение будет выбрано на основе настройки контейнера.$arguments– аргументы для конструктора PHP-класса.$tags– тег с метаданными.$setups– внедрение зависимостей через сеттер-метод [2] [3].$resetter– значение для сброса состояния объекта.$isLazy– объявить «ленивый объект».
Идентификатор контейнера для PHP-класса
При объявлении PHP-класса через атрибут \Kaspi\DiContainer\Attributes\Autowire пустая строка в параметре $id интерпретируется контейнером как идентификатор контейнера представленный FQCN[4] объявляемого PHP-класса.
Объявить PHP-класс \App\Services\Foo через атрибут, идентификатор контейнера должен быть строкой 'App\Services\Foo', и объявить внедрение скалярного значения 'Lorem ipsum' в параметр конструктора класса $value.
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use Kaspi\DiContainer\Attributes\Autowire;
#[Autowire(arguments: ['Lorem ipsum'])]
final class Foo
{
public function __construct(public readonly string $value) {}
}<?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);
var_dump($foo->value);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
string(11) "Lorem ipsum"Объявление PHP-класса с несколькими идентификаторами
Атрибут \Kaspi\DiContainer\Attributes\Autowire может объявлять один и тот же PHP-класс в контейнере с разными идентификаторами[1:1].
Объявить PHP-класс \App\Services\Bar через атрибут, идентификатор контейнера должен быть представлен строкой 'App\Services\Bar', и объявить внедрение скалярного значения 10 в параметр конструктора $value.
Объявить PHP-класс \App\Services\Bar через атрибут, идентификатор контейнера должен быть представлен строкой 'services.bar_20', и объявить внедрение скалярного значения 20 в параметр конструктора $value.
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use Kaspi\DiContainer\Attributes\Autowire;
#[Autowire(arguments: [10])]
#[Autowire(id: 'services.bar_20', arguments: [20])]
final class Bar
{
public function __construct(public readonly int $value) {}
}<?php
declare(strict_types=1);
// file: /app/src/container_build.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Bar;
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$bar = $container->get(Bar::class);
var_dump($bar->value);
$bar20 = $container->get('services.bar_20');
var_dump($bar20->value);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
int(10)
int(20)Аргументы конструктора PHP-класса
Параметр $arguments атрибута \Kaspi\DiContainer\Attributes\Autowire передает аргументы конструктору PHP-класса.
При объявлении внедрения зависимости в конкретный параметр, указывайте в качестве ключа массива в $arguments имя этого параметра.
Параметры не получившие аргументы через $arguments будут внедрены контейнером самостоятельно, на основании конфигурации.
В аргументах можно использовать классы других определений контейнера.
Kaspi\DiContainer\DiDefinition\DiDefinitionAutowire– PHP-класс.Kaspi\DiContainer\DiDefinition\DiDefinitionCallable– внедряет зависимость через вызовcallableтипа.Kaspi\DiContainer\DiDefinition\DiDefinitionFactory– фабрика для внедрения зависимости.Kaspi\DiContainer\DiDefinition\DiDefinitionGet– внедрение зависимостей посредством ссылки на идентификатор контейнера.Kaspi\DiContainer\DiDefinition\DiDefinitionParameter– внедрение зависимости из параметров контейнера.Kaspi\DiContainer\DiDefinition\DiDefinitionParameterRutime– внедрение зависимости из параметров контейнера времени выполнения.Kaspi\DiContainer\DiDefinition\DiDefinitionProxyClosure– внедрение зависимости через «ленивую загрузку».Kaspi\DiContainer\DiDefinition\DiDefinitionRuntime– внедрение объекта времени выполнения.Kaspi\DiContainer\DiDefinition\DiDefinitionTaggedAs– внедрение зависимости - коллекция по тегу.
Пример объявления аргументов для конструктора PHP-класса
PHP-классы:
<?php
declare(strict_types=1);
// file: /app/src/Services/FooService.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class FooService
{
public function __construct(
public readonly BatService $bat,
public readonly QuxInterface $qux,
public readonly string $adminEmail
) {}
}<?php
declare(strict_types=1);
// file: /app/src/Services/BarService.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class BarService implements QuxInterface
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Services/BazService.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class BazService implements QuxInterface
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Services/BatService.php
namespace App\Services;
final class BatService
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Interfaces/QuxInterface.php
namespace App\Interfaces;
interface QuxInterface
{
// …
}Необходимо объявить PHP-класс \App\Services\FooService с разными идентификаторами контейнера и аргументами.
<?php
declare(strict_types=1);
// file: /app/src/Services/FooService.php
namespace App\Services;
use Kaspi\DiContainer\Attributes\Autowire;
use Kaspi\DiContainer\DiDefinition\{
DiDefinitionGet as DiGet,
DiDefinitionParameter as DiParameter
};
use App\Interfaces\QuxInterface;
#[Autowire(
arguments: [
'qux' => new DiGet(BarService::class),
'adminEmail' => new DiParameter('emails.bar'),
]
)]
#[Autowire(
id: 'services.foo_service.with_baz',
arguments: [
'qux' => new DiGet(BazService::class),
'adminEmail' => new DiParameter('emails.baz'),
]
)]
final class FooService
{
public function __construct(
public readonly BatService $bat,
public readonly QuxInterface $qux,
public readonly string $adminEmail
) {}
}<?php
declare(strict_types=1);
// file: /app/src/container_build.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\{FooService, BarService, BazService, BatService};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->addParameters([
'emails.bar' => 'manager@example.com',
'emails.baz' => 'admin@example.com',
])
->build();
$fooService = $container->get(FooService::class);
var_dump($fooService->bat::class);
var_dump($fooService->qux::class);
var_dump($fooService->adminEmail);
$fooServiceWithBaz = $container->get('services.foo_service.with_baz');
echo PHP_EOL;
var_dump($fooServiceWithBaz->bat::class);
var_dump($fooServiceWithBaz->qux::class);
var_dump($fooServiceWithBaz->adminEmail);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
string(23) "App\Services\BatService"
string(23) "App\Services\BarService"
string(19) "manager@example.com"
string(23) "App\Services\BatService"
string(23) "App\Services\BazService"
string(16) "admin@example.comВнедрение зависимостей через сеттер-методы
Параметр $setups атрибута \Kaspi\DiContainer\Attributes\Autowire объявляет внедрение зависимости через сеттер-методы PHP-класса, используя атрибуты \Kaspi\DiContainer\Attributes\Setup и \Kaspi\DiContainer\Attributes\SetupImmutable.
Значение null в параметре $setups указывает контейнеру на необходимость внедрять зависимости через атрибуты Setup и SetupImmutable указанные у методов класса.
Значение [] (пустой массив) в параметре $setups указывает контейнеру не внедрять зависимости через сеттер-методы, даже если у методов класса указаны атрибуты Setup и SetupImmutable.
<?php
declare(strict_types=1);
namespace App\Services;
use Kaspi\DiContainer\Attributes\Autowire;
use Kaspi\DiContainer\Attributes\Setup;
use Kaspi\DiContainer\Attributes\SetupImmutable;
use Kaspi\DiContainer\DiDefinition\DiDefinitionGet as DiGet;
use Kaspi\DiContainer\DiDefinition\DiDefinitionParameter as Parameter;
#[Autowire(
setups: [
'bar' => new Setup(
new Parameter('params.api_key')
),
'baz' => new SetupImmutable(
new DiGet(Baz::class)
),
]
)]
final class Foo
{
// …
public function bar(string $apiKey): void
{
// …
}
public function baz(QuxInterface $qux): self
{
// …
}
}Теги
Параметр $tags атрибута \Kaspi\DiContainer\Attributes\Autowire устанавливает тег и метаданные для объявляемого PHP-класса, используя атрибут \Kaspi\DiContainer\Attributes\Tag.
Значение null в параметре $tags указывает контейнеру на необходимость установить тег через атрибут Tag указанный в объявляемом PHP-классе.
Значение [] (пустой массив) в параметре $tags указывает контейнеру не устанавливать тег к объявляемому PHP-классу, даже если у класса указан атрибут Tag.
<?php
declare(strict_types=1);
namespace App\Services;
use Kaspi\DiContainer\Attributes\Autowire;
use Kaspi\DiContainer\Attributes\Tag;
#[Autowire(
tags: [
new Tag('tags.fuze'),
new Tag('tags.internal_service'),
]
)]
final class Foo
{
// …
}Внедрения зависимости в параметр метода или вызываемого типа
Объявить внедрение PHP-класса в параметр метода или вызываемого тип[5] можно через атрибут \Kaspi\DiContainer\Attributes\Autowire.
Значение в параметре $id атрибута Autowire может быть указано пустой строкой или строкой FQCN[4:1].
Пустая строка в параметре $id атрибута Autowire будет интерпретирована контейнером как тип параметра[6] для которого применяется атрибут.
Пример объявления внедрения в параметр метода
PHP-классы:
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use App\Interfaces\QuxInterface;
class Foo
{
public function __construct(
public readonly QuxInterface $qux,
public readonly Baz $baz,
) {}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Bar.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Bar implements QuxInterface
{
public function __construct(public readonly string $notifyEmail) {}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Baz.php
namespace App\Services;
final class Baz
{
public function __construct(
public readonly string $email = 'baz@localhost'
) {}
}<?php
declare(strict_types=1);
// file: /app/src/Interfaces/QuxInterface.php
namespace App\Interfaces;
interface QuxInterface
{
// …
}Для PHP-класса \App\Services\Foo объявить внедрение в параметры конструктора $qux и $baz через атрибут Kaspi\DiContainer\Attributes\Autowire.
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use App\Interfaces\QuxInterface;
use Kaspi\DiContainer\Attributes\Autowire;
use Kaspi\DiContainer\DiDefinition\DiDefinitionParameter as DiParameter;
class Foo
{
public function __construct(
#[Autowire(
id: Bar::class,
arguments: [
new DiParameter('emails.bar')
]
)]
public readonly QuxInterface $qux,
#[Autowire(
arguments: [
new DiParameter('emails.baz')
]
)]
public readonly Baz $baz,
) {}
}<?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, Bar, Baz};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->addParameters([
'emails.bar' => 'manager@example.com',
'emails.baz' => 'admin@example.com',
])
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux->notifyEmail);
var_dump($foo->baz->email);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
string(19) "manager@example.com"
string(16) "admin@example.com"Идентификатор контейнера (Container ID) – это строковое имя (или имя класса/интерфейса), по которому сервис или объект зарегистрирован и запрашивается из контейнера через метод
get(). ↩︎ ↩︎Мутабельный сеттер-метод — это метод для изменения значения внутреннего свойства объекта, который модифицирует существующий объект на месте и обычно возвращает
void. ↩︎Иммутабельный сеттер-метод — это метод, который не изменяет текущий объект, а создаёт и возвращает его новый экземпляр с обновлённым значением. ↩︎
Fully Qualified Class Name – полное имя класса или интерфейса, включая пространство имён. ↩︎ ↩︎
Вызываемый тип –
callable, представляет значения или выражения, доступные для вызова как функция. Описание в документации PHP. ↩︎Type hints – указание ожидаемого типа данных для параметров метода, например имя конкретного класса или интерфейса. ↩︎