yiisoft/yii-event

2.1.0 2023-11-04 15:57 UTC

This package is auto-updated.

Last update: 2024-09-13 19:29:01 UTC


README

Yii

Yii 事件


Latest Stable Version Total Downloads Build status Code coverage Mutation testing badge static analysis type-coverage

此包是 yiisoft/event-dispatcher 包的配置包装器。它的目的是使事件监听器声明比您能想象的任何时候都要简单。您只需要使用任何兼容 PSR-11 的 DI 容器。

需求

  • PHP 8.1 或更高版本。

安装

此包可以使用 Composer 安装。

composer require yiisoft/yii-event

通用用法

DI 配置

您可以在 config 目录 中找到默认配置。

所有这些设置都将自动在具有 yiisoft/config 的项目中使用。

如果您有自定义的 events 配置组名称,例如 events-api,请在该 eventsConfigGroup 参数键中重新定义它。

params.php

return [
    'yiisoft/yii-event' => [
        'eventsConfigGroup' => 'events-api',
    ],
]

事件配置示例

配置是一个数组,键是事件名称,值是处理器数组

return [
    EventName::class => [
        // Just a regular closure, it will be called from the Dispatcher "as is".
        static fn (EventName $event) => someStuff($event),
        
        // A regular closure with additional dependency. All the parameters after the first one (the event itself)
        // will be resolved from your DI container within `yiisoft/injector`.
        static fn (EventName $event, DependencyClass $dependency) => someStuff($event),
        
        // An example with a regular callable. If the `staticMethodName` method contains some dependencies,
        // they will be resolved the same way as in the previous example.
        [SomeClass::class, 'staticMethodName'],
        
        // Non-static methods are allowed too. In this case `SomeClass` will be instantiated by your DI container.
        [SomeClass::class, 'methodName'],
        
        // An object of a class with the `__invoke` method implemented
        new InvokableClass(),
        
        // In this case the `InvokableClass` with the `__invoke` method will be instantiated by your DI container
        InvokableClass::class,
        
        // Any definition of an invokable class may be here while your `$container->has('the definition)` 
        'di-alias'
    ],
];

依赖关系解析是以懒加载方式完成的:在相应事件发生之前不会解析依赖关系。

配置检查器

为了帮助您进行事件监听器配置验证,有一个 ListenerConfigurationChecker。它将您的整个监听器配置一次转换为实际的调用者以进行验证。它旨在用于开发环境或测试中,因为它是大型项目中资源密集型操作。如果您的配置包含无效的监听器,将抛出 InvalidEventConfigurationFormatException

用法示例

$checker->check($configuration->get('events-web'));

文档

如果您需要帮助或有任何问题,Yii 论坛 是一个好地方。您还可以查看其他 Yii 社区资源

许可

Yii 事件是免费软件。它根据 BSD 许可证的条款发布。有关更多信息,请参阅 LICENSE

Yii软件维护。

支持该项目

Open Collective

关注更新

Official website Twitter Telegram Facebook Slack