yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.91k forks source link

yii\base\Event data property have been overrided when i calling trigger. #10614

Closed shamyyl closed 8 years ago

shamyyl commented 8 years ago

I triggered the MyClass::EVENT_SEND_EMAIL:

$this->trigger(MyClass::EVENT_SEND_EMAIL, new Event(['data' => 'somedata']));

Before that I had been attached the event handler by next code:

Event::on(MyClass::className(),MyClass::EVENT_SEND_EMAIL,function($event){
     var_dump($event->data); 
});

this code: var_dump($event->data) returns null. Because of that code in yii\base\Component::trigger function:

...
$event->data = $handler[1]; // 541 line
...

But i dont want to provide data in Event when attaching handler. I want to provide this when calling the trigger.

So, is this a bug or a feature?! And how i can provide my special data for each trigger calling?

SilverFire commented 8 years ago

The behavior is expected. Create your own class MailSendEvent like so:

class EmailSendEvent extends Event
{
     public $payload;
}

and then call

$this->trigger(MyClass::EVENT_SEND_EMAIL, new EmailSendEvent(['payload' => 'somedata']));

I'd suggest you to take a look at command bus pattern implementation http://tactician.thephpleague.com/ and Yii2 adapter for it: https://github.com/trntv/yii2-tactician It's a little bit more complex, but maybe you'll like it.