Пример внедрения в конкретный параметр
При объявлении внедрения в параметр метода или вызываемого типа[1] ожидающего объект реализующий определённый интерфейс, можно уточнить какую именно реализацию внедрять. При таком объявлении внедряемый PHP-класс может отличаться от глобально объявленной реализации интерфейса.
PHP-классы
<?php
declare(strict_types=1);
// file: /app/src/Interfaces/QuxInterface.php
namespace App\Interfaces;
interface QuxInterface
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Foo
{
public function __construct(
public readonly QuxInterface $qux
) {}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Qux.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Qux
{
public function __construct(
public readonly QuxInterface $qux
) {}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Bar.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Bar implements QuxInterface
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Services/Baz.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Baz implements QuxInterface
{
// …
}Необходимо объявить реализацию интерфейса \App\Interfaces\QuxInterface PHP-классом \App\Services\Bar, т.е. чтобы контейнер автоматически внедрял в параметр метода на основании конфигурации.
Для PHP-класса \App\Services\Qux необходимо объявить внедрение зависимости в параметр конструктора $qux PHP-класса \App\Services\Baz, обратите внимание: внедряемый класса реализуют интерфейс \App\Interfaces\QuxInterface.
Хелпер функции
В файле конфигураций services.php указана основная реализация интерфейса \App\Interfaces\QuxInterface PHP-классом \App\Services\Bar.
<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Interfaces\QuxInterface;
use App\Service\Bar;
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield QuxInterface::class => diAutowire(Bar::class);
};Это означает что в любой параметр с типом \App\Interfaces\QuxInterface будет внедрён объект PHP-класса \App\Service\Bar.
diAutowire()
Файл конфигураций services_qux.php использует хелпер функцию diAutowire() чтобы объявить внедрение в параметр конструктора $qux PHP-класса \App\Services\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, Qux};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->load('/app/config/services.php')
->load('/app/config/services_qux.php')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux);
$qux = $container->get(Qux::class);
var_dump($qux->qux);<?php
declare(strict_types=1);
// file: /app/config/services_qux.php
use App\Services\{Qux, Baz};
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield diAutowire(Qux::class)
->bindArguments(
qux: diAutowire(Baz::class)
);
};<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Interfaces\QuxInterface;
use App\Service\Bar;
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield QuxInterface::class => diAutowire(Bar::class);
};Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#2 (0) {
}
object(App\Services\Baz)#4 (0) {
}diCallable()
В некоторых случая когда требуется сложная инициализация PHP-класса процесс создания такого объекта можно делегировать любому вызываемому типу[1:1].
Файл конфигураций services_qux.php использует хелпер функцию diCallable() чтобы объявить 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, Qux};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->load('/app/config/services.php')
->load('/app/config/services_qux.php')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux);
$qux = $container->get(Qux::class);
var_dump($qux->qux);<?php
declare(strict_types=1);
// file: /app/config/services_qux.php
use App\Services\{Qux, Baz};
use function Kaspi\DiContainer\{diAutowire, diCallable};
return static function (): Generator {
// Сложная сборка PHP-класса
$fn = static function (): Baz {
$baz = new Baz();
// тут возможны дополнительные действия с $baz
return $baz;
};
yield diAutowire(Qux::class)
->bindArguments(
qux: diCallable($fn)
);
};<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Interfaces\QuxInterface;
use App\Service\Bar;
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield QuxInterface::class => diAutowire(Bar::class);
};Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#2 (0) {
}
object(App\Services\Baz)#4 (0) {
}Подсказка
Аналогичное объявление можно сделать через хелпер функцию diFactory().
diGet()
Если определение PHP-класса — со всеми необходимыми внедрениями зависимостей и конфигурациями — уже существует в контейнере и доступно через его метод get(), то при определении реализации для интерфейса можно просто указать ссылку на существующий в контейнере идентификатор этого PHP-класса.
Файл конфигураций services_qux.php использует хелпер функцию diGet() для объявления внедрения в параметр.
<?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, Qux};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->load('/app/config/services.php')
->load('/app/config/services_qux.php')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux);
$qux = $container->get(Qux::class);
var_dump($qux->qux);<?php
declare(strict_types=1);
// file: /app/config/services_qux.php
use App\Services\{Qux, Baz};
use function Kaspi\DiContainer\{diAutowire, diGet};
return static function (): Generator {
yield diAutowire(Baz::class);
// … many lines
yield diAutowire(Qux::class)
->bindArguments(
qux: diGet(Baz::class)
);
};<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Interfaces\QuxInterface;
use App\Service\Bar;
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield QuxInterface::class => diAutowire(Bar::class);
};Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#2 (0) {
}
object(App\Services\Baz)#4 (0) {
}Атрибуты
Реализация интерфейса \App\Interfaces\QuxInterface объявлена PHP-классом \App\Services\Bar глобально через атрибут \Kaspi\DiContainer\Attributes\Service.
<?php
declare(strict_types=1);
// file: /app/src/Interfaces/QuxInterface.php
namespace App\Interfaces;
use App\Service\Bar;
use Kaspi\DiContainer\Attributes\Service;
#[Service(Bar::class)]
interface QuxInterface
{
// …
}Это означает что в любой параметр с типом \App\Interfaces\QuxInterface будет внедрён объект PHP-класса \App\Service\Bar.
Autowire
Параметр конструктора $qux PHP-класса \App\Services\Qux представлен типом \App\Interfaces\QuxInterface, необходимо объявить внедрение в этот параметр другой реализации интерфейса, а именно PHP-класс \App\Services\Baz. Объявить внедрение можно через атрибут \Kaspi\DiContainer\Attributes\Autowire.
Замечание
Здесь приведён простой пример использования атрибута. При объявлении внедрения PHP-класса через атрибут доступны все возможности атрибута, включая объявления аргументов конструктора и внедрений через сеттер-методы.
<?php
declare(strict_types=1);
// file: /app/src/Services/Qux.php
namespace App\Services;
use App\Interfaces\QuxInterface;
use Kaspi\DiContainer\Attributes\Autowire;
final class Qux
{
public function __construct(
#[Autowire(Bar::class)]
public readonly QuxInterface $qux
) {}
}<?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, Qux};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux);
$qux = $container->get(Qux::class);
var_dump($qux->qux);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#2 (0) {
}
object(App\Services\Baz)#4 (0) {
}InjectByCallable
При объявлении реализации интерфейса может потребоваться сложная сборка PHP-класса, поэтому этот процесс можно делегировать любому вызываемому типу[1:2].
В этом примере в качестве вызываемого типа выступает статический метод PHP-класса – \App\Helpers\FactoryCreate::makeService(), а объявить внедрение можно через атрибут \Kaspi\DiContainer\Attributes\InjectByCallable.
<?php
declare(strict_types=1);
// file: /app/src/Helpers/FactoryCreate.php
namespace App\Helpers;
use App\Services\Baz;
final class FactoryCreate
{
// Сложная сборка PHP-класса
public static function makeService(): Baz
{
$baz = new Baz();
// тут возможны дополнительные действия с $baz
return $baz;
}
}<?php
declare(strict_types=1);
// file: /app/src/Services/Qux.php
namespace App\Services;
use App\Interfaces\QuxInterface;
use Kaspi\DiContainer\Attributes\InjectByCallable;
use App\Helpers\FactoryCreate;
final class Qux
{
public function __construct(
#[InjectByCallable([
FactoryCreate::class,
'makeService',
)]
public readonly QuxInterface $qux
) {}
}<?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, Qux};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux);
$qux = $container->get(Qux::class);
var_dump($qux->qux);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#2 (0) {
}
object(App\Services\Baz)#4 (0) {
}Inject
В случае если в контейнере уже объявлен PHP-класс, с указанием всех необходимых внедрений и настроек, и он доступен для метода контейнера get(), то можно использовать атрибут \Kaspi\DiContainer\Attributes\Inject для объявления внедрения в параметр.
<?php
declare(strict_types=1);
// file: /app/src/Services/Qux.php
namespace App\Services;
use App\Interfaces\QuxInterface;
use Kaspi\DiContainer\Attributes\Inject;
final class Qux
{
public function __construct(
#[Inject(Bar::class)]
public readonly QuxInterface $qux
) {}
}<?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, Qux};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->qux);
$qux = $container->get(Qux::class);
var_dump($qux->qux);Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#2 (0) {
}
object(App\Services\Baz)#4 (0) {
}Вызываемый тип –
callable, представляет значения или выражения, доступные для вызова как функция. Описание в документации PHP. ↩︎ ↩︎ ↩︎