Skip to content

Instantly share code, notes, and snippets.

@SilverFire
Created November 29, 2015 20:52
Show Gist options
  • Save SilverFire/467b2def3115ecc38c43 to your computer and use it in GitHub Desktop.
Save SilverFire/467b2def3115ecc38c43 to your computer and use it in GitHub Desktop.

Events using interfaces

There is even more abstract way to deal with events. You can create a separated interface for the special event and implement it in classes, where you need it.

For example we can create the following interface:

interface DanceEventInterface
{
    const EVENT_DANCE = 'dance';
}

And two classes, that implement it:

class Dog extends Component implements DanceEventInterface
{
    public function meetBuddy()
    {
        echo "Woof!";
        $this->trigger(DanceEventInterface::EVENT_DANCE);
    }
}

class Developer extends Component implements DanceEventInterface
{
    public function testsPassed()
    {
        echo "Yay!";
        $this->trigger(DanceEventInterface::EVENT_DANCE);
    }
}

To handle the EVENT_DANCE, triggered by any of these classes, call [[yii\base\Event::on()]] and pass the interface name as the first argument:

Event::on('DanceEventInterface', DanceEventInterface::EVENT_DANCE, function ($event) {
    Yii::trace($event->sender->className . ' just danced'); // Will log that Dog or Developer danced
})

You can trigger the event of those classes:

Event::trigger(DanceEventInterface::className(), DanceEventInterface::EVENT_DANCE);

But please notice, that you can not trigger all the classes, that implement the interface:

// DOES NOT WORK
Event::trigger('DanceEventInterface', DanceEventInterface::EVENT_DANCE); // error

Do detach event handler, call [[yii\base\Event::off()]]. For example:

// detaches $handler
Event::off('DanceEventInterface', DanceEventInterface::EVENT_DANCE, $handler);

// detaches all handlers of DanceEventInterface::EVENT_DANCE
Event::off('DanceEventInterface', DanceEventInterface::EVENT_DANCE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment