Контейнер: привязки, singleton и сборка аргументов
This commit is contained in:
1 parent
aaa08522e9
commit
9075c817dc
5 files changed
+484
-51
No files matched your search
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Привязки контейнера: что подставлять, когда просят тип.
|
||||
*
|
||||
* Свои классы (App\ и Rsgrinko\Proton\) контейнер собирает и без записи здесь —
|
||||
* реестр нужен для интерфейсов, чужих классов и всего, чему при сборке нужны
|
||||
* настройки.
|
||||
*
|
||||
* 'bind' => [Storage::class => LocalStorage::class],
|
||||
* 'singleton' => [PriceList::class => static fn (Container $c) => new PriceList(...)],
|
||||
*
|
||||
* bind — новый объект на каждый запрос зависимости, singleton — один на процесс.
|
||||
* Для воркера «один на процесс» значит «до перезапуска»: объект с настройками
|
||||
* внутри переживёт их правку в панели.
|
||||
*/
|
||||
|
||||
return [
|
||||
'bind' => [
|
||||
],
|
||||
|
||||
'singleton' => [
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,83 @@
|
||||
# Контейнер зависимостей
|
||||
|
||||
`Support\Container` собирает объекты и подставляет их туда, где они нужны:
|
||||
в конструкторы контроллеров, в действия маршрутов, в любой вызов через `call()`.
|
||||
|
||||
Свои классы (`App\`, `Rsgrinko\Proton\`) он собирает без всяких записей — достаточно
|
||||
типа. Реестр нужен интерфейсам, чужим классам и всему, чему при сборке нужны
|
||||
настройки.
|
||||
|
||||
## Привязки
|
||||
|
||||
```php
|
||||
$container = Container::instance();
|
||||
|
||||
$container->bind(Storage::class, LocalStorage::class); // каждый раз новый объект
|
||||
$container->singleton(PriceList::class); // один на процесс
|
||||
$container->set(Clock::class, new FrozenClock()); // готовый объект (тесты)
|
||||
$container->bind(HttpClient::class, static fn (Container $c): HttpClient => new HttpClient(30));
|
||||
```
|
||||
|
||||
Привязки приложения живут в `config/services.php` и подхватываются сами:
|
||||
|
||||
```php
|
||||
return [
|
||||
'bind' => [
|
||||
App\Contracts\Storage::class => App\Services\LocalStorage::class,
|
||||
],
|
||||
'singleton' => [
|
||||
App\Services\PriceList::class => static fn (Container $c) => new PriceList(
|
||||
$c->make(Rsgrinko\Proton\Database\Connection::class)
|
||||
),
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
Класс без привязки собирается **каждый раз заново**. Общими бывают только те, кого
|
||||
об этом попросили: долгий процесс воркера иначе копил бы объекты с устаревшими
|
||||
настройками внутри.
|
||||
|
||||
## Сборка и вызов
|
||||
|
||||
```php
|
||||
$controller = $container->make(NotesController::class);
|
||||
$report = $container->make(MonthReport::class, ['month' => '2026-09']); // скаляр по имени
|
||||
|
||||
$container->call([$report, 'build'], ['period' => 'месяц']);
|
||||
```
|
||||
|
||||
В `make()` и `call()` аргументы ищутся так: сначала переданные по имени, потом
|
||||
по типу из контейнера, потом значение по умолчанию, потом `null` для допускающего
|
||||
его параметра. Не нашлось — исключение с именем аргумента и местом:
|
||||
«Не могу подставить «period» в App\Reports\MonthReport::build()».
|
||||
|
||||
Кольцо зависимостей ловится и называется целиком:
|
||||
«Зависимости закольцевались: A → B → A», а не вешает процесс.
|
||||
|
||||
## В действиях маршрутов
|
||||
|
||||
Роутер подставляет в метод контроллера `Request`, параметры адреса (`{id}`),
|
||||
атрибуты запроса от прослоек (`$user`, `$viewer`, `$scope`) — и всё остальное
|
||||
с типом-классом собирает контейнер:
|
||||
|
||||
```php
|
||||
public function index(Request $request, Scope $scope, PriceList $prices): Response
|
||||
```
|
||||
|
||||
Имена атрибутов важнее типов: `User $current` работать не будет, потому что
|
||||
атрибут называется `user`. Модели контейнер не собирает вовсе — модель это
|
||||
строка таблицы, а не зависимость, и подставленная пустая модель молчала бы
|
||||
вместо понятной ошибки.
|
||||
|
||||
## Тесты
|
||||
|
||||
Контейнер подменяется целиком:
|
||||
|
||||
```php
|
||||
Container::setInstance(null); // забыть всё, что настроили
|
||||
$container = new Container();
|
||||
$container->set(HttpClient::class, new FakeClient());
|
||||
Container::setInstance($container);
|
||||
```
|
||||
|
||||
Раннер делает это сам между тестами-хозяевами (`withOwnDatabase`).
|
||||
@@ -357,6 +357,14 @@ final class Router
|
||||
continue;
|
||||
}
|
||||
|
||||
// Всё остальное с типом-классом собирает контейнер: так в действие
|
||||
// просят сервис, а не тащат его через конструктор контроллера
|
||||
if ($type instanceof ReflectionNamedType && !$type->isBuiltin() && Container::instance()->has($type->getName())) {
|
||||
$arguments[] = Container::instance()->make($type->getName());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($parameter->isDefaultValueAvailable()) {
|
||||
$arguments[] = $parameter->getDefaultValue();
|
||||
|
||||
|
||||
+235
-51
@@ -4,25 +4,44 @@ declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Closure;
|
||||
use ReflectionClass;
|
||||
use ReflectionFunction;
|
||||
use ReflectionFunctionAbstract;
|
||||
use ReflectionMethod;
|
||||
use ReflectionNamedType;
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
|
||||
/**
|
||||
* Маленький сборщик объектов: создаёт класс, подставляя в конструктор то, что он
|
||||
* просит по типам. Нужен роутеру, чтобы контроллеры получали зависимости, а не
|
||||
* создавали их сами — тогда в тестах можно подложить свои.
|
||||
* Сборщик объектов: создаёт класс, подставляя в конструктор то, что он просит
|
||||
* по типам, а во что превращается интерфейс — решает реестр привязок.
|
||||
*
|
||||
* Никакой магии: свои классы (Rsgrinko\Proton\ и App\), общее подключение к базе
|
||||
* и значения по умолчанию.
|
||||
* $container->bind(Storage::class, LocalStorage::class); // каждый раз новый
|
||||
* $container->singleton(PriceList::class); // один на процесс
|
||||
* $container->set(Clock::class, new FrozenClock()); // готовый объект
|
||||
* $container->make(NotesController::class);
|
||||
* $container->call([$report, 'build'], ['period' => 'месяц']);
|
||||
*
|
||||
* Привязки приложения перечисляются в `config/services.php` и подхватываются
|
||||
* сами при первом обращении.
|
||||
*
|
||||
* Своё поведение по умолчанию: класс без привязки собирается каждый раз заново.
|
||||
* Общими бывают только те, кого об этом попросили (`singleton`, `set`), — иначе
|
||||
* долгий процесс воркера копил бы объекты с устаревшими настройками внутри.
|
||||
*/
|
||||
final class Container
|
||||
{
|
||||
/** @var array<string, object> Уже созданные объекты */
|
||||
/** @var array<string, object> Готовые объекты: общие на весь процесс */
|
||||
private array $shared = [];
|
||||
|
||||
/** @var array<string, callable> Свои сборщики: класс => функция */
|
||||
private array $factories = [];
|
||||
/** @var array<string, array{concrete: Closure|string, shared: bool}> Привязки */
|
||||
private array $bindings = [];
|
||||
|
||||
/** @var array<int, string> Что собираем прямо сейчас — им ловятся кольца */
|
||||
private array $building = [];
|
||||
|
||||
private bool $booted = false;
|
||||
|
||||
private static ?self $instance = null;
|
||||
|
||||
@@ -42,106 +61,271 @@ final class Container
|
||||
/**
|
||||
* Положить готовый объект: его и будут получать все, кто просит этот тип.
|
||||
*/
|
||||
public function set(string $class, object $object): self
|
||||
public function set(string $abstract, object $object): self
|
||||
{
|
||||
$this->shared[$class] = $object;
|
||||
$this->shared[$abstract] = $object;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Своя сборка типа — когда конструктор просит то, чего контейнер не знает.
|
||||
* Привязка: что создавать, когда просят $abstract. Без второго аргумента —
|
||||
* сам класс; строка — класс-замена (обычно реализация интерфейса);
|
||||
* замыкание — своя сборка, ему передаётся контейнер.
|
||||
*/
|
||||
public function bind(string $class, callable $factory): self
|
||||
public function bind(string $abstract, Closure|string|null $concrete = null, bool $shared = false): self
|
||||
{
|
||||
$this->factories[$class] = $factory;
|
||||
$this->bindings[$abstract] = ['concrete' => $concrete ?? $abstract, 'shared' => $shared];
|
||||
|
||||
unset($this->shared[$abstract]);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт класс со всеми зависимостями.
|
||||
* То же, но объект создаётся один раз на процесс.
|
||||
*/
|
||||
public function singleton(string $abstract, Closure|string|null $concrete = null): self
|
||||
{
|
||||
return $this->bind($abstract, $concrete, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Знает ли контейнер, что делать с типом.
|
||||
*/
|
||||
public function has(string $abstract): bool
|
||||
{
|
||||
$this->boot();
|
||||
|
||||
return isset($this->shared[$abstract]) || isset($this->bindings[$abstract]) || $this->own($abstract);
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт объект со всеми зависимостями. Значения, которые не вывести по
|
||||
* типу (числа, строки), передаются по имени аргумента.
|
||||
*
|
||||
* @template T of object
|
||||
*
|
||||
* @param class-string<T> $class
|
||||
* @param class-string<T> $abstract
|
||||
* @param array<string, mixed> $arguments
|
||||
*
|
||||
* @return T
|
||||
*/
|
||||
public function make(string $class): object
|
||||
public function make(string $abstract, array $arguments = []): object
|
||||
{
|
||||
if (isset($this->shared[$class])) {
|
||||
$this->boot();
|
||||
|
||||
if (isset($this->shared[$abstract])) {
|
||||
/** @var T $shared */
|
||||
$shared = $this->shared[$class];
|
||||
$shared = $this->shared[$abstract];
|
||||
|
||||
return $shared;
|
||||
}
|
||||
|
||||
if (isset($this->factories[$class])) {
|
||||
/** @var T $built */
|
||||
$built = ($this->factories[$class])($this);
|
||||
|
||||
return $this->shared[$class] = $built;
|
||||
if (in_array($abstract, $this->building, true)) {
|
||||
throw new ProtonException(
|
||||
'Зависимости закольцевались: ' . implode(' → ', [...$this->building, $abstract])
|
||||
);
|
||||
}
|
||||
|
||||
// Подключение к базе одно на процесс
|
||||
if ($class === Connection::class) {
|
||||
/** @var T $connection */
|
||||
$connection = Connection::instance();
|
||||
$this->building[] = $abstract;
|
||||
|
||||
return $connection;
|
||||
try {
|
||||
$object = $this->build($abstract, $arguments);
|
||||
} finally {
|
||||
array_pop($this->building);
|
||||
}
|
||||
|
||||
$reflection = new ReflectionClass($class);
|
||||
$constructor = $reflection->getConstructor();
|
||||
|
||||
if ($constructor === null) {
|
||||
/** @var T $object */
|
||||
$object = new $class();
|
||||
|
||||
return $this->shared[$class] = $object;
|
||||
if (($this->bindings[$abstract]['shared'] ?? false) === true) {
|
||||
$this->shared[$abstract] = $object;
|
||||
}
|
||||
|
||||
$arguments = [];
|
||||
/** @var T $object */
|
||||
return $object;
|
||||
}
|
||||
|
||||
foreach ($constructor->getParameters() as $parameter) {
|
||||
/**
|
||||
* Вызывает метод или функцию, подставляя аргументы: по имени — из
|
||||
* $arguments, остальное — по типам из контейнера.
|
||||
*
|
||||
* @param callable|array{0: object|class-string, 1: string} $callback
|
||||
* @param array<string, mixed> $arguments
|
||||
*/
|
||||
public function call(callable|array $callback, array $arguments = []): mixed
|
||||
{
|
||||
$this->boot();
|
||||
|
||||
if (is_array($callback)) {
|
||||
$object = is_string($callback[0]) ? $this->make($callback[0]) : $callback[0];
|
||||
$method = new ReflectionMethod($object, $callback[1]);
|
||||
$arguments = $this->arguments($method, $arguments);
|
||||
|
||||
return $method->invokeArgs($object, $arguments);
|
||||
}
|
||||
|
||||
$function = new ReflectionFunction(Closure::fromCallable($callback));
|
||||
|
||||
return $function->invokeArgs($this->arguments($function, $arguments));
|
||||
}
|
||||
|
||||
/**
|
||||
* Аргументы для вызова: сначала переданные по имени, потом собранные по типу.
|
||||
*
|
||||
* @param array<string, mixed> $arguments
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
public function arguments(ReflectionFunctionAbstract $function, array $arguments = []): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach ($function->getParameters() as $parameter) {
|
||||
$name = $parameter->getName();
|
||||
$type = $parameter->getType();
|
||||
|
||||
if ($type instanceof ReflectionNamedType && !$type->isBuiltin() && $this->known($type->getName())) {
|
||||
$arguments[] = $this->make($type->getName());
|
||||
if (array_key_exists($name, $arguments)) {
|
||||
$values[] = $arguments[$name];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($type instanceof ReflectionNamedType && !$type->isBuiltin() && $this->has($type->getName())) {
|
||||
$values[] = $this->make($type->getName());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($parameter->isDefaultValueAvailable()) {
|
||||
$arguments[] = $parameter->getDefaultValue();
|
||||
$values[] = $parameter->getDefaultValue();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($parameter->allowsNull()) {
|
||||
$arguments[] = null;
|
||||
$values[] = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new ProtonException(
|
||||
'Не могу собрать ' . $class . ': непонятно, что передать в «' . $parameter->getName() . '»'
|
||||
'Не могу подставить «' . $name . '» в ' . $this->where($function)
|
||||
);
|
||||
}
|
||||
|
||||
/** @var T $object */
|
||||
$object = $reflection->newInstanceArgs($arguments);
|
||||
|
||||
return $this->shared[$class] = $object;
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Свой ли это класс. Чужие (и встроенные) контейнер не собирает — там слишком
|
||||
* легко получить объект не с теми настройками.
|
||||
* Привязки приложения из config/services.php.
|
||||
*
|
||||
* @param array{bind?: array<string, Closure|string>, singleton?: array<string, Closure|string>} $services
|
||||
*/
|
||||
private function known(string $class): bool
|
||||
public function register(array $services): self
|
||||
{
|
||||
return str_starts_with($class, 'Rsgrinko\\Proton\\') || str_starts_with($class, 'App\\');
|
||||
foreach ((array) ($services['bind'] ?? []) as $abstract => $concrete) {
|
||||
$this->bind((string) $abstract, $concrete);
|
||||
}
|
||||
|
||||
foreach ((array) ($services['singleton'] ?? []) as $abstract => $concrete) {
|
||||
$this->singleton((string) $abstract, $concrete);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arguments
|
||||
*/
|
||||
private function build(string $abstract, array $arguments): object
|
||||
{
|
||||
$concrete = $this->bindings[$abstract]['concrete'] ?? $abstract;
|
||||
|
||||
if ($concrete instanceof Closure) {
|
||||
$object = $concrete($this, $arguments);
|
||||
|
||||
if (!is_object($object)) {
|
||||
throw new ProtonException('Сборщик для ' . $abstract . ' вернул не объект');
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
if ($concrete !== $abstract) {
|
||||
return $this->make($concrete, $arguments);
|
||||
}
|
||||
|
||||
if (!class_exists($concrete)) {
|
||||
throw new ProtonException(
|
||||
'Нечего создать для ' . $abstract . ': это интерфейс или неизвестный класс, привязки для него нет'
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
$reflection = new ReflectionClass($concrete);
|
||||
|
||||
if (!$reflection->isInstantiable()) {
|
||||
throw new ProtonException('Класс ' . $concrete . ' сам по себе не создаётся — нужна привязка');
|
||||
}
|
||||
|
||||
$constructor = $reflection->getConstructor();
|
||||
|
||||
if ($constructor === null) {
|
||||
return new $concrete();
|
||||
}
|
||||
|
||||
return $reflection->newInstanceArgs($this->arguments($constructor, $arguments));
|
||||
}
|
||||
|
||||
/**
|
||||
* Свой ли это класс. По типу подставляются только свои классы и то, у чего
|
||||
* есть привязка: чужой объект слишком легко получить не с теми настройками.
|
||||
* Прямой `make()` соберёт и чужой класс, если сможет, — там просят явно.
|
||||
*/
|
||||
private function own(string $class): bool
|
||||
{
|
||||
if (!str_starts_with($class, 'Rsgrinko\\Proton\\') && !str_starts_with($class, 'App\\')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Модель — это строка таблицы, а не зависимость: собранная контейнером,
|
||||
// она пришла бы пустой, и вместо понятной ошибки получилась бы тишина
|
||||
return class_exists($class) && !is_subclass_of($class, Model::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Где именно не хватило аргумента — иначе по сообщению не найти место.
|
||||
*/
|
||||
private function where(ReflectionFunctionAbstract $function): string
|
||||
{
|
||||
if ($function instanceof ReflectionMethod) {
|
||||
return $function->getDeclaringClass()->getName() . '::' . $function->getName() . '()';
|
||||
}
|
||||
|
||||
return $function->getName() . '()';
|
||||
}
|
||||
|
||||
/**
|
||||
* Привязки ядра и приложения. Читаются один раз, лениво: контейнер создаётся
|
||||
* и в консоли, и в воркере, а конфиг может быть ещё не нужен.
|
||||
*/
|
||||
private function boot(): void
|
||||
{
|
||||
if ($this->booted) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->booted = true;
|
||||
|
||||
// Подключение к базе одно на процесс и создаётся не конструктором
|
||||
$this->singleton(Connection::class, static fn (): Connection => Connection::instance());
|
||||
|
||||
$file = APP_ROOT . '/config/services.php';
|
||||
|
||||
if (is_file($file)) {
|
||||
/** @var array{bind?: array<string, Closure|string>, singleton?: array<string, Closure|string>} $services */
|
||||
$services = (array) require $file;
|
||||
|
||||
$this->register($services);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Контейнер: привязки, singleton, сборка аргументов и вызов методов.
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\Container;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
interface ContainerTestStorage
|
||||
{
|
||||
public function name(): string;
|
||||
}
|
||||
|
||||
final class ContainerTestLocal implements ContainerTestStorage
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'локальное';
|
||||
}
|
||||
}
|
||||
|
||||
final class ContainerTestReport
|
||||
{
|
||||
public function __construct(public readonly Logger $logger)
|
||||
{
|
||||
}
|
||||
|
||||
public function build(string $period, Logger $logger): string
|
||||
{
|
||||
return $period . ':' . spl_object_id($logger);
|
||||
}
|
||||
}
|
||||
|
||||
final class ContainerTestLeft
|
||||
{
|
||||
public function __construct(public readonly ContainerTestRight $right)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
final class ContainerTestRight
|
||||
{
|
||||
public function __construct(public readonly ContainerTestLeft $left)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
test('контейнер: привязка интерфейса к классу', function (): void {
|
||||
$container = new Container();
|
||||
$container->bind(ContainerTestStorage::class, ContainerTestLocal::class);
|
||||
|
||||
assertSame('локальное', $container->make(ContainerTestStorage::class)->name());
|
||||
assertTrue($container->has(ContainerTestStorage::class));
|
||||
|
||||
$error = assertThrows(static fn () => (new Container())->make(ContainerTestStorage::class));
|
||||
|
||||
assertTrue($error instanceof ProtonException, 'интерфейс без привязки не собирается');
|
||||
});
|
||||
|
||||
test('контейнер: singleton один на процесс, обычная привязка — каждый раз новая', function (): void {
|
||||
$container = new Container();
|
||||
|
||||
$container->singleton(ContainerTestLocal::class);
|
||||
|
||||
assertTrue($container->make(ContainerTestLocal::class) === $container->make(ContainerTestLocal::class));
|
||||
|
||||
// Без привязки класс собирается заново: общими бывают только те, кого просили
|
||||
assertFalse($container->make(ContainerTestReport::class) === $container->make(ContainerTestReport::class));
|
||||
});
|
||||
|
||||
test('контейнер: замыкание получает контейнер и создаёт объект само', function (): void {
|
||||
$container = new Container();
|
||||
|
||||
$container->singleton(Logger::class, static fn (): Logger => new Logger('через замыкание'));
|
||||
|
||||
$report = $container->make(ContainerTestReport::class);
|
||||
|
||||
assertTrue($report->logger === $container->make(Logger::class));
|
||||
});
|
||||
|
||||
test('контейнер: вызов метода подставляет и значения, и зависимости', function (): void {
|
||||
$container = new Container();
|
||||
$container->singleton(Logger::class, static fn (): Logger => new Logger('вызов'));
|
||||
|
||||
$result = $container->call([ContainerTestReport::class, 'build'], ['period' => 'месяц']);
|
||||
|
||||
assertSame('месяц:' . spl_object_id($container->make(Logger::class)), $result);
|
||||
|
||||
// Значения, которое не вывести по типу, не хватает — и об этом сказано прямо
|
||||
$error = assertThrows(static fn () => $container->call([ContainerTestReport::class, 'build']));
|
||||
|
||||
assertContains('period', $error->getMessage());
|
||||
assertContains('ContainerTestReport::build', $error->getMessage());
|
||||
});
|
||||
|
||||
test('контейнер: кольцо зависимостей ловится, а не вешает процесс', function (): void {
|
||||
$container = new Container();
|
||||
|
||||
$container->bind(ContainerTestLeft::class)->bind(ContainerTestRight::class);
|
||||
|
||||
$error = assertThrows(static fn () => $container->make(ContainerTestLeft::class));
|
||||
|
||||
assertContains('закольцевались', $error->getMessage());
|
||||
});
|
||||
|
||||
test('контейнер: модели и чужие классы сам не собирает', function (): void {
|
||||
$container = new Container();
|
||||
|
||||
assertFalse($container->has(User::class), 'модель — это запись, а не зависимость');
|
||||
assertFalse($container->has(DateTimeZone::class));
|
||||
|
||||
$error = assertThrows(static fn () => $container->make(DateTimeZone::class));
|
||||
|
||||
assertTrue($error instanceof ProtonException);
|
||||
});
|
||||
|
||||
test('контейнер: реестр services.php разбирается', function (): void {
|
||||
$container = new Container();
|
||||
|
||||
$container->register([
|
||||
'bind' => [ContainerTestStorage::class => ContainerTestLocal::class],
|
||||
'singleton' => [Logger::class => static fn (): Logger => new Logger('из реестра')],
|
||||
]);
|
||||
|
||||
assertSame('локальное', $container->make(ContainerTestStorage::class)->name());
|
||||
assertTrue($container->make(Logger::class) === $container->make(Logger::class));
|
||||
});
|
||||
Reference in new issue
Block a user