2021-05-13 997次浏览

Yii event is the first framework-specific package from Yii 3 family. Its goal is to make configuring events convenient. For the applications it provides three main config files:

  • events.php - Common event handlers for web and console.
  • events-web.php - Web event handlers.
  • events-console.php - Console event handlers. The config syntax is the following:

    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'
     ],
    

    ];

For convenience, there's a configuration checker that is used in current application templates to check if all handlers declared are correct.