yiicod/yii2-listener

The simple and powerful event listener for the Yii2 framework

Installs: 9 621

Dependents: 0

Suggesters: 0

Security: 0

Stars: 14

Watchers: 4

Forks: 5

Open Issues: 0

Type:yii2-extension

1.0.7 2018-04-09 20:21 UTC

This package is auto-updated.

Last update: 2024-10-27 00:46:45 UTC


README

Latest Stable Version Total Downloads Scrutinizer Code QualityCode Climate

Provides listener logic. Command parses chosen paths to find all listener/subscribers (depends on ListenerInterface and SubscriberInterface implementation). Where listener can be used for single event and subscriber can be used for bunch of events.

Installation

Either run

php composer.phar require --prefer-dist yiicod/yii2-listener "*"

or add

"yii2-listener": "*"

to your composer.json file

Web config

'bootstrap' => ['listener'],
'components' => [
    'listener' => [
        'class' => 'yiicod\listener\components\Listener'
    ],
]

Console config

'controllerMap' => [
    'listener' => [
        'class' => \yiicod\listener\commands\Listener::class
    ],
]

Run command. This command will warm and prepare all listeners and subscriptions. Run this command each time when you create new Listener or Subscription.

listener/parse

For trigger event use yii manual: http://www.yiiframework.com/doc-2.0/guide-concept-events.html#class-level-event-handlers

Listener usage

namespace frontend\observers\listeners;

use yii\db\ActiveRecord;
use yiicod\listener\components\listeners\ListenerAbstract;

class TestListener extends ListenerAbstract
{
   /**
    * Call on event method
    */
   public function handle($event)
   {
       // TODO: Implement handle() method.
   }

   /**
    * Return event name for emit
    * @return string
    */
   public static function event(): string
   {
       return ActiveRecord::class . '@' . ActiveRecord::EVENT_AFTER_FIND;
   }
}

Usage subscriber

namespace frontend\observers\subscribers;

use yii\db\ActiveRecord;
use yiicod\listener\components\listeners\SubscriberAbstract;

class TestSubscriber extends SubscriberAbstract
{
   /**
    * @return array
    * [
    *      'event_class@event1' => 'on'
    *      'event_class@event2' => 'on'
    * ]
    */
   public static function subscribe(): array
   {
       return [
           ActiveRecord::class . '@' . ActiveRecord::EVENT_BEFORE_INSERT => 'on',
           ActiveRecord::class . '@' . ActiveRecord::EVENT_AFTER_INSERT => 'on'
       ];
   }

   /**
    * Call on event method
    */
   public function on($event)
   {
       // Handle
   }
}