-
Using the Messenger Service Instead of drupal_set_message in Drupal 8
/ June 7, 2018As you may know, drupal_set_message() is deprecated in Drupal 8.5.0.
Here’s a quick example of using dependency injection to use the new Messenger service:
mymodule.services.yml
YAML1234services:mymodule.authentication:class: Drupal\mymodule\MymoduleAuthenticationarguments: ['@messenger']src/MymoduleAuthentication.php
PHP1234567891011121314151617181920212223242526272829303132333435<?phpnamespace Drupal\mymodule;use Drupal\Core\Messenger\MessengerInterface;/*** Provides authentication functionality for my module.** @package Drupal\mymodule*/class MymoduleAuthentication {/*** Include the messenger service.** @var \Drupal\Core\Messenger\MessengerInterface*/protected $messenger;/*** Constructor.*/public function __construct(MessengerInterface $messenger) {$this->messenger = $messenger;}/*** Shows a "Hello, world" message.*/private function showHelloWorldMessage() {$this->messenger->addMessage('Hello, world');}}