M
M
Mikha Pankratov2015-12-03 19:20:26
Yii
Mikha Pankratov, 2015-12-03 19:20:26

What is the correct way to do events in Yii2?

Good afternoon,
I want to make sending mail after registration an event.
I'll make an event.

namespace app\event;

use yii\base\Component;
use yii\base\Event;

class MessageEvent extends Event
{
    public $message;
    
    public function send($message)
    {
        return \Yii::$app->get('mailer')->compose(['html' => 'actiovationAuthKey-text'], ['user' => ['first_name' => 'asdfasdfsa'])
                        ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
                        ->setTo('[email protected]')
                        ->setSubject('$message)
                        ->send();
    }
   
}

and after validating and saving the user, I make a call and a trigger.
$event = new app\event\MessageEvent;
                $event->message = 'sadf';
                $this->trigger(self::EVENT_MESSAGE_SENT, $event);

Tell me what am I doing wrong? there are no errors and the message did not come) so I'm guessing, thanks for the help. I'm sorry, first experience with events.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Khomenko, 2015-12-03
@frmax

In your case, there is no part that is subscribed to the event. You excite him, but no one listens to him.
Here is your example, via global events only:

class MessageSendEvent extends Event
{
    const EVENT_MESSAGE_SEND = 'message-send-event';

    /**
     * @var string
     */
    public $message;

    /**
     * ...
     */
    public function send ()
    {
        echo $this->message;
    }
}

Now we subscribe and "listen" to the event:
# Вешаем обработчик события
Yii::$app->on( MessageSendEvent::EVENT_MESSAGE_SEND, function ( MessageSendEvent $event ) {
    $event->send();
} );

And at the right moment we excite it:
# Инициируем событие
Yii::$app->trigger(
    MessageSendEvent::EVENT_MESSAGE_SEND,
    new MessageSendEvent( [
        'message' => 'Сообщение!'
    ] )
);

But damn, you have such an overhead here that it makes no sense to use such an example. It's easier to call ->send() yourself and that's it, without any events there.
UPD: The Event object, it is essentially a data carrier. He does NOT have to do the work himself. It only has to deliver the necessary data to the worker, and the worker contains all the logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question