Answer the question
In order to leave comments, you need to log in
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();
}
}
$event = new app\event\MessageEvent;
$event->message = 'sadf';
$this->trigger(self::EVENT_MESSAGE_SENT, $event);
Answer the question
In order to leave comments, you need to log in
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;
}
}
# Вешаем обработчик события
Yii::$app->on( MessageSendEvent::EVENT_MESSAGE_SEND, function ( MessageSendEvent $event ) {
$event->send();
} );
# Инициируем событие
Yii::$app->trigger(
MessageSendEvent::EVENT_MESSAGE_SEND,
new MessageSendEvent( [
'message' => 'Сообщение!'
] )
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question