Внедрение зависимостей через сеттер-методы
Внедрение зависимостей в PHP-класс может происходить через сеттер-методы.
Объявить внедрение зависимостей через сеттер-методы можно через методы setup(), setupImmutable() предоставляемые хелпер функцией diAutowire() или атрибуты \Kaspi\DiContainer\Attributes\Setup, \Kaspi\DiContainer\Attributes\SetupImmutable.
Мутабельный сеттер-метод[1]
PHP-классы:
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Foo
{
private QuxInterface $qux;
public function setQux(QuxInterface $qux): void
{
$this->qux = $qux;
}
public function getQux(): ?QuxInterface
{
return $this->qux ?? null;
}
}<?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/Bar.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Bar implements QuxInterface
{
// …
}Необходимо объявить внедрение в PHP-класа \App\Services\Bar через мутабельный сеттер-метод \App\Services\Foo::setQux().
Параметр $qux метода \App\Services\Foo::setQux() ожидает объект реализующий интерфейс \App\Interfaces\QuxInterface. Контейнер предоставляет множество способов объявления внедрения PHP-класса в параметр, для этого примера будет использована хелпер функция diGet() или атрибут \Kaspi\DiContainer\Attributes\Inject в зависимости от способа объявления внедрения зависимости.
Объявление в файлах конфигураций
В файле конфигураций services.php объявим PHP-класс \App\Services\Foo и объявление внедрения через сеттер-метод 'setQux'.
<?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')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->getQux());<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Service\{Foo, Bar};
use function Kaspi\DiContainer\{diAutowire, diGet};
return static function (): Generator {
yield diAutowire(Foo::class)
->setup(
'setQux',
[
'qux' => diGet(Bar::class),
],
);
};Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#23 (0) {
}Объявление через атрибут
Объявим внедрение PHP-класса \App\Services\Bar через атрибут \Kaspi\DiContainer\Attributes\Setup, указав его для сеттер-метода \App\Services\Foo::setQux(). Для объявления внедрения в параметр сеттер-метода используем атрибут \Kaspi\DiContainer\Attributes\Inject.
<?php
declare(strict_types=1);
// file: /app/src/Services/Foo.php
namespace App\Services;
use App\Interfaces\QuxInterface;
use Kaspi\DiContainer\Attributes\Inject;
use Kaspi\DiContainer\Attributes\Setup;
final class Foo
{
private QuxInterface $qux;
public function setQux(QuxInterface $qux): void
#[Setup]
public function setQux(
#[Inject(Bar::class)]
QuxInterface $qux
): void
{
// …<?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->getQux());Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#23 (0) {
}Иммутабельный сеттер-метод[2]
PHP-классы:
<?php
declare(strict_types=1);
// file: /app/src/Services/Baz.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Baz
{
private QuxInterface $qux;
public function withQux(QuxInterface $qux): self
{
$new = clone $this;
$new->qux = $qux;
return $new;
}
public function getQux(): ?QuxInterface
{
return $this->qux ?? null;
}
}<?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/Bar.php
namespace App\Services;
use App\Interfaces\QuxInterface;
final class Bar implements QuxInterface
{
// …
}Необходимо объявить внедрение в PHP-класа \App\Services\Bar через иммутабельный сеттер-метод \App\Services\Baz::withQux(). Обратите внимание, сеттер-метод возвращает новый объект класса \App\Services\Baz.
Параметр $qux метода \App\Services\Baz::withQux() ожидает объект реализующий интерфейс \App\Interfaces\QuxInterface. Контейнер предоставляет множество способов объявления внедрения PHP-класса в параметр, для этого примера будет использована хелпер функция diGet() или атрибут \Kaspi\DiContainer\Attributes\Inject в зависимости от способа объявления внедрения зависимости.
Объявление в файлах конфигураций
В файле конфигураций services.php объявим PHP-класс \App\Services\Baz и объявление внедрения через сеттер-метод 'withQux'.
<?php
declare(strict_types=1);
// file: /app/src/container_build.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Baz;
$container = (new DiContainerBuilder())
->load('/app/config/services.php')
->build();
$baz = $container->get(Baz::class);
var_dump($baz->getQux());<?php
declare(strict_types=1);
// file: /app/config/services.php
use App\Service\{Baz, Bar};
use function Kaspi\DiContainer\{diAutowire, diGet};
return static function (): Generator {
yield diAutowire(Baz::class)
->setupImmutable(
'withQux',
[
'qux' => diGet(Bar::class),
],
);
};Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#23 (0) {
}Объявление через атрибут
Объявим внедрение PHP-класса \App\Services\Bar через атрибут \Kaspi\DiContainer\Attributes\SetupImmutable, указав его для сеттер-метода \App\Services\Baz::withQux(). Для объявления внедрения в параметр сеттер-метода используем атрибут \Kaspi\DiContainer\Attributes\Inject.
<?php
declare(strict_types=1);
// file: /app/src/Services/Baz.php
namespace App\Services;
use App\Interfaces\QuxInterface;
use Kaspi\DiContainer\Attributes\Inject;
use Kaspi\DiContainer\Attributes\SetupImmutable;
final class Baz
{
private QuxInterface $qux;
public function withQux(QuxInterface $qux): self
#[SetupImmutable]
public function withQux(
#[Inject(Bar::class)]
QuxInterface $qux
): void
{
// …<?php
declare(strict_types=1);
// file: /app/src/container_build.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Baz;
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->build();
$baz = $container->get(Baz::class);
var_dump($baz->getQux());Выполните в терминале команду:
php /app/src/container_build.phpПоявится сообщение вида:
object(App\Services\Bar)#23 (0) {
}Внедрение нескольких зависимостей
Рассмотрим на примере внедрения нескольких зависимостей через один мутабельный[1:1] сеттер-метод \App\Services\Rules::addRule().
Для объявления внедрения зависимостей используем атрибут \Kaspi\DiContainer\Attributes\Setup.
Параметр $inputRule сеттер-метода ожидает объект реализующий интерфейс \App\Interfaces\RuleInterface. Контейнер предоставляет множество способов объявления внедрения PHP-класса в параметр, для этого примера будет использована PHP-класс \Kaspi\DiContainer\DiDefinition\DiDefinitionGet.
В аргументах можно использовать классы других определений контейнера.
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
declare(strict_types=1);
// file: /app/src/container.php
require_once __DIR__.'/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\Rules;
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src/')
->build();
$rules = $container->get(Rules::class);
foreach($rules->getRules() as $rule) {
var_dump($rule);
print PHP_EOL;
}<?php
declare(strict_types=1);
// file: /app/src/Services/Rules.php
namespace App\Services;
use Kaspi\DiContainer\Attributes\Setup;
use Kaspi\DiContainer\DiDefinition\DiDefinitionGet as DiGet;
use App\Rules\{RuleA, RuleB};
use App\Interfaces\RuleInterface;
class Rules
{
private array $rules = [];
// …
#[Setup(
new DiGet(RuleB::class)
)]
#[Setup(
new DiGet(RuleA::class)
)]
public function addRule(RuleInterface $inputRule): void
{
$this->rules[] = $inputRule;
}
public function getRules(): array
{
return $this->rules;
}
}<?php
declare(strict_types=1);
// file: /app/src/Interfaces/RuleInterface.php
namespace App\Interfaces;
interface RuleInterface
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Rules/RuleA.php
namespace App\Rules;
use App\Interfaces\RuleInterface;
class RuleA implements RuleInterface
{
// …
}<?php
declare(strict_types=1);
// file: /app/src/Rules/RuleB.php
namespace App\Rules;
use App\Interfaces\RuleInterface;
class RuleB implements RuleInterface
{
// …
}Выполните в терминале команду:
php /app/src/container.phpПоявится сообщение вида:
object(App\Rules\RuleB)#2 (0) {
}
object(App\Rules\RuleA)#2 (0) {
}Очерёдность внедренных объектов через сеттер-метод обусловлена порядком применения атрибута \Kaspi\DiContainer\Attributes\Setup к методу \App\Services\RuleGenerator::addRule().
Мутабельный сеттер-метод — это метод для изменения значения внутреннего свойства объекта, который модифицирует существующий объект на месте и обычно возвращает
void. ↩︎ ↩︎Иммутабельный сеттер-метод — это метод, который не изменяет текущий объект, а создаёт и возвращает его новый экземпляр с обновлённым значением. ↩︎