Хелпер функция diProxyClosure()
Хелпер функция diProxyClosure() внедряет «ленивую» зависимость через встроенный PHP-класс \Closure, откладывая инициализацию зависимости до момента фактического его использования.
Такой приём объявления зависимости пригодится для внедрения «тяжёлых» зависимостей, требующих длительного времени инициализации или ресурсоёмкий вычислений.
Важно
Обязательно типизировать параметр[1] как \Closure или callable для внедрения зависимости через хелпер функцию diProxyClosure().
public function __construct(
private readonly \Closure $bar
) {}Подсказка
Если используется PHP 8.4 и выше, то вместо хелпер функции diProxyClosure() предпочтительнее внедрять зависимость через встроенный в PHP механизм «ленивых объектов».
Сигнатура функции:
use Kaspi\DiContainer\Interfaces\DiDefinition\DiDefinitionTagArgumentInterface;
\Kaspi\DiContainer\diProxyClosure(
string $containerIdentifier,
?bool $isSingleton = null,
): DiDefinitionTagArgumentInterfaceПараметры:
$containerIdentifier– идентификатор контейнера [2].$isSingleton– возвращать один и тот же результат (паттерн singleton). Если значение null, то значение будет выбрано на основе настройки контейнера.
Функция diProxyClosure() возвращает объект предоставляющий методы:
bindTag()– добавляет тег с метаданными для определения.
bindTag()
Теги позволяют отнести «ленивое» определение к коллекции элементов отмеченных одним тегом.
Метод bindTag() описан интерфейсом \Kaspi\DiContainer\Interfaces\DiDefinition\DiDefinitionTagArgumentInterface.
Сигнатура метода:
DiDefinitionTagArgumentInterface::bindTag(
string $name,
array $options = [],
null|int|string $priority = null
)Подсказка
Более подробное описание работы с тегами.
Идентификатор контейнера для «ленивого» определения
Чтобы обеспечить доступность «ленивого» определения через метод контейнера get() и has() необходимо указать в файле конфигураций идентификатор контейнера[2:1] соответствующий объявленному определению.
Ресурсоёмкий PHP-класс требующий длительной инициализации:
<?php
declare(strict_types=1);
// file: /app/src/Services/Bar.php
namespace App\Services;
final class Bar
{
/*
* A class that requires a long initialization time
* and involves resource-intensive computations.
*/
}Метод контейнера $container->get('services.bar_lazy') должен возвращать «ленивый» объект класса \App\Services\Bar.
<?php
declare(strict_types=1);
// file: /app/src/container.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Bar;
$container = (new DiContainerBuilder())
->load('/app/config/lazy_entries.php')
->build();
$barLazy = $container->get('services.bar_lazy');
var_dump($barLazy instanceof Closure);
var_dump(($barLazy)() instanceof Bar);<?php
declare(strict_types=1);
// file: /app/config/lazy_entries.php
use App\Services\Bar;
use function Kaspi\DiContainer\diProxyClosure;
return static function(): Generator {
yield 'services.bar_lazy' => diProxyClosure(
Bar::class,
isSingleton: true
);
};Выполните в терминале команду:
php /app/src/container.phpПоявится сообщение вида:
bool(true)
bool(true)Пример внедрения параметра с отложенной инициализацией
PHP-классы:
<?php
declare(strict_types=1);
// file: /app/src/Services/Bar.php
namespace App\Services;
final class Bar
{
/*
* A class that requires a long initialization time
* and involves resource-intensive computations.
*/
}<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use Closure;
final class Foo
{
/**
* @param Closure(): Bar $barProxy
*/
public function __construct(private readonly Closure $barProxy) {}
public function getBar(): Bar
{
return ($this->barProxy)();
}
}PHP-класс \App\Services\Bar при инициализации производит ресурсоёмкие вычисления, его внедрить в параметр $barProxy конструктора PHP-класса \App\Services\Foo используя приём «ленивой» инициализации объекта через встроенный в PHP-класс \Closure.
<?php
declare(strict_types=1);
// file: /app/src/container.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\{Foo, Bar};
$container = (new DiContainerBuilder())
->load('/app/config/services.php')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->getBar() instanceof Bar);<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Services\{Foo, Bar};
use function Kaspi\DiContainer\{diAutowire, diProxyClosure};
return static function(): Generator {
yield diAutowire(Foo::class)
->bindArguments(
barProxy: diProxyClosure(Bar::class)
);
};Выполните в терминале команду:
php /app/src/container.phpПоявится сообщение вида:
bool(true)Подсказка
Используйте PhpDocBlock для подсказок и автодополнения в IDE:
/**
* @param Closure(): Bar $barProxy
*/
public function __construct(private readonly Closure $barProxy) {}Type hints – указание ожидаемого типа данных для параметров метода, например имя конкретного класса или интерфейса. ↩︎
Идентификатор контейнера (Container ID) – это строковое имя (или имя класса/интерфейса), по которому сервис или объект зарегистрирован и запрашивается из контейнера через метод
get(). ↩︎ ↩︎