Skip to content

Система прокси

ADP использует паттерн прокси для прозрачного перехвата вызовов PSR-интерфейсов. Прокси оборачивают стандартные PSR-реализации и передают перехваченные данные коллекторам без изменения кода приложения.

Как это работает

Прокси реализует тот же PSR-интерфейс, что и оригинальный сервис. Он делегирует все вызовы реальной реализации, одновременно записывая данные для парного коллектора.

Код приложения


┌─────────────────┐
│  PSR-интерфейс   │  ← Код вызывает как обычно
│  (напр. Logger)  │
└────────┬────────┘

┌────────▼────────┐
│     Прокси       │  ← Перехватывает + записывает
│ (LoggerProxy)    │
└────────┬────────┘

┌────────▼────────┐
│ Реальный сервис  │  ← Оригинальная реализация
│ (Monolog и т.д.) │
└────────┬────────┘

┌────────▼────────┐
│   Коллектор      │  ← Получает записанные данные
│ (LogCollector)   │
└─────────────────┘

Встроенные прокси

Ядро предоставляет фреймворко-независимые PSR-прокси:

ПроксиPSR-интерфейсПарный коллектор
LoggerInterfaceProxyAppDevPanel\Kernel\Collector\LoggerInterfaceProxyDecorator proxy for Logger Interface. Intercepts calls and forwards data to collectors.final Kernel · class · implements LoggerInterfacePSR-3 LoggerInterfacePsr\Log\LoggerInterfacePSR-3 Logger Interface. Describes a logger instance.PSR-3 · interfaceLogCollectorAppDevPanel\Kernel\Collector\LogCollectorCollects Log data during application lifecycle.Kernel · class · implements SummaryCollectorInterface
EventDispatcherInterfaceProxyAppDevPanel\Kernel\Collector\EventDispatcherInterfaceProxyDecorator proxy for Event Dispatcher Interface. Intercepts calls and forwards data to collectors.final Kernel · class · implements EventDispatcherInterfacePSR-14 EventDispatcherInterfacePsr\EventDispatcher\EventDispatcherInterfacePSR-14 Event Dispatcher Interface. Defines a dispatcher for events.PSR-14 · interfaceEventCollectorAppDevPanel\Kernel\Collector\EventCollectorCollects Event data during application lifecycle.final Kernel · class · implements SummaryCollectorInterface
HttpClientInterfaceProxyAppDevPanel\Kernel\Collector\HttpClientInterfaceProxyDecorator proxy for Http Client Interface. Intercepts calls and forwards data to collectors.final Kernel · class · implements ClientInterfacePSR-18 ClientInterfacePsr\Http\Client\ClientInterfacePSR-18 HTTP Client Interface. Sends PSR-7 requests and returns PSR-7 responses.PSR-18 · interfaceHttpClientCollectorAppDevPanel\Kernel\Collector\HttpClientCollectorCollects Http Client data during application lifecycle.final Kernel · class · implements SummaryCollectorInterface

Прокси фреймворков

Адаптеры фреймворков предоставляют дополнительные прокси для интерфейсов, не стандартизированных PSR:

ПроксиФреймворкИнтерфейсПарный коллектор
SymfonyTranslatorProxyAppDevPanel\Adapter\Symfony\Proxy\SymfonyTranslatorProxyDecorates Symfony's TranslatorInterface to feed translation lookups to TranslatorCollector.final Adapter/Symfony · class · implements TranslatorInterfaceSymfonyTranslatorInterfaceSymfony\Contracts\Translation\TranslatorInterfaceSymfony Translation Contract. Translates messages using message catalogs.Symfony · interfaceTranslatorCollectorAppDevPanel\Kernel\Collector\TranslatorCollectorCaptures translation lookups during request execution.final Kernel · class · implements SummaryCollectorInterface
SymfonyEventDispatcherProxyAppDevPanel\Adapter\Symfony\Proxy\SymfonyEventDispatcherProxyWraps Symfony's event dispatcher to intercept dispatched events.final Adapter/Symfony · class · implements EventDispatcherInterfaceSymfonyEventDispatcherInterfaceSymfony\Contracts\EventDispatcher\EventDispatcherInterfaceSymfony Event Dispatcher Contract. Dispatches events to registered listeners.Symfony · interfaceEventCollectorAppDevPanel\Kernel\Collector\EventCollectorCollects Event data during application lifecycle.final Kernel · class · implements SummaryCollectorInterface
LaravelTranslatorProxyAppDevPanel\Adapter\Laravel\Proxy\LaravelTranslatorProxyDecorates Laravel's Translator to feed translation lookups to TranslatorCollector.final Adapter/Laravel · class · implements TranslatorLaravelTranslatorIlluminate\Contracts\Translation\TranslatorLaravel Translator Contract. Provides translation services for the application.Laravel · interfaceTranslatorCollectorAppDevPanel\Kernel\Collector\TranslatorCollectorCaptures translation lookups during request execution.final Kernel · class · implements SummaryCollectorInterface
LaravelEventDispatcherProxyAppDevPanel\Adapter\Laravel\Proxy\LaravelEventDispatcherProxyWraps Laravel's event dispatcher to intercept dispatched events.final Adapter/Laravel · class · implements DispatcherLaravelDispatcherEventCollectorAppDevPanel\Kernel\Collector\EventCollectorCollects Event data during application lifecycle.final Kernel · class · implements SummaryCollectorInterface
TranslatorInterfaceProxyAppDevPanel\Adapter\Yii3\Collector\Translator\TranslatorInterfaceProxyDecorates Yiisoft TranslatorInterface to feed translation lookups to TranslatorCollector.final Adapter/Yii3 · class · implements TranslatorInterfaceYii 3TranslatorInterfaceTranslatorCollectorAppDevPanel\Kernel\Collector\TranslatorCollectorCaptures translation lookups during request execution.final Kernel · class · implements SummaryCollectorInterface
ValidatorInterfaceProxyAppDevPanel\Adapter\Yii3\Collector\Validator\ValidatorInterfaceProxyDecorator proxy for Validator Interface. Intercepts calls and forwards data to collectors.final Adapter/Yii3 · class · implements ValidatorInterfaceYii 3ValidatorInterfaceValidatorCollectorAppDevPanel\Kernel\Collector\ValidatorCollectorCaptures validation operations with results.final Kernel · class · implements SummaryCollectorInterface
ContainerInterfaceProxyAppDevPanel\Adapter\Yii3\Proxy\ContainerInterfaceProxyDecorator proxy for Container Interface. Intercepts calls and forwards data to collectors.final Adapter/Yii3 · class · implements ContainerInterfaceYii 3PSR-11 ContainerInterfacePsr\Container\ContainerInterfacePSR-11 Container Interface. Describes the interface of a dependency injection container.PSR-11 · interfaceServiceCollectorAppDevPanel\Kernel\Collector\ServiceCollectorCollects Service data during application lifecycle.final Kernel · class · implements SummaryCollectorInterface
I18NProxyAppDevPanel\Adapter\Yii2\Proxy\I18NProxyDecorates Yii 2's I18N component to feed translation lookups to TranslatorCollector.final Adapter/Yii2 · class · extends I18NYii 2yii\i18n\I18NTranslatorCollectorAppDevPanel\Kernel\Collector\TranslatorCollectorCaptures translation lookups during request execution.final Kernel · class · implements SummaryCollectorInterface

Прокси переводчика

У каждого фреймворка свой интерфейс переводчика. ADP предоставляет выделенный прокси для каждого, все они передают данные в один TranslatorCollectorAppDevPanel\Kernel\Collector\TranslatorCollectorCaptures translation lookups during request execution.final Kernel · class · implements SummaryCollectorInterface. Подробности на странице Переводчик.

Symfony -- SymfonyTranslatorProxyAppDevPanel\Adapter\Symfony\Proxy\SymfonyTranslatorProxyDecorates Symfony's TranslatorInterface to feed translation lookups to TranslatorCollector.final Adapter/Symfony · class · implements TranslatorInterface декорирует TranslatorInterfaceSymfony\Contracts\Translation\TranslatorInterfaceSymfony Translation Contract. Translates messages using message catalogs.Symfony · interface через setDecoratedService() в compiler pass. Перехватывает вызовы trans().

Laravel -- LaravelTranslatorProxyAppDevPanel\Adapter\Laravel\Proxy\LaravelTranslatorProxyDecorates Laravel's Translator to feed translation lookups to TranslatorCollector.final Adapter/Laravel · class · implements Translator декорирует TranslatorIlluminate\Contracts\Translation\TranslatorLaravel Translator Contract. Provides translation services for the application.Laravel · interface через $app->extend('translator'). Перехватывает вызовы get() и choice(). Разбирает точечную нотацию ключей Laravel (group.key) на категорию и сообщение.

Yii 3 -- TranslatorInterfaceProxyAppDevPanel\Adapter\Yii3\Collector\Translator\TranslatorInterfaceProxyDecorates Yiisoft TranslatorInterface to feed translation lookups to TranslatorCollector.final Adapter/Yii3 · class · implements TranslatorInterface регистрируется в trackedServices наряду с ValidatorInterfaceProxyAppDevPanel\Adapter\Yii3\Collector\Validator\ValidatorInterfaceProxyDecorator proxy for Validator Interface. Intercepts calls and forwards data to collectors.final Adapter/Yii3 · class · implements ValidatorInterface. Перехватывает вызовы translate(). Поддерживает иммутабельные методы withDefaultCategory() и withLocale().

Yii 2 -- I18NProxyAppDevPanel\Adapter\Yii2\Proxy\I18NProxyDecorates Yii 2's I18N component to feed translation lookups to TranslatorCollector.final Adapter/Yii2 · class · extends I18N наследует yii\i18n\I18N и переопределяет translate(). Заменяет компонент приложения i18n при загрузке модуля.

Обнаружение отсутствующих переводов

Все прокси определяют отсутствие перевода, сравнивая возвращённое значение переводчика с исходным идентификатором сообщения. Если они совпадают, перевод помечается как missing.

Трейт ProxyDecoratedCalls

Трейт ProxyDecoratedCalls предоставляет магические методы __call, __get и __set, которые делегируют вызовы обёрнутому сервису. Прокси используют этот трейт для прозрачной переадресации неперехватываемых вызовов.

Регистрация прокси

Прокси регистрируются адаптерами фреймворков через конфигурацию DI-контейнера. Адаптер заменяет оригинальную привязку PSR-сервиса на прокси:

php
// Упрощённая DI-конфигурация адаптера
LoggerInterface::class => function (ContainerInterface $c) {
    return new LoggerInterfaceProxy(
        $c->get(LogCollector::class),
        $c->get('original.logger'),
    );
},

Ключевые принципы

  • Прозрачность -- код приложения не знает о перехвате
  • Нулевые затраты при отключении -- прокси регистрируются только при активном ADP
  • PSR-совместимость -- прокси реализуют тот же интерфейс, что и оригинальный сервис
  • Колокация -- каждый прокси находится рядом с парным коллектором в src/Collector/

Выпущено под лицензией MIT.