Using the Messenger Service Instead of drupal_set_message in Drupal 8
June 7, 2018
/
As 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
YAML
1 2 3 4 |
services: mymodule.authentication: class: Drupal\mymodule\MymoduleAuthentication arguments: ['@messenger'] |
src/MymoduleAuthentication.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php namespace 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'); } } |
One Comment
Binny Thomas
Thanks. This helped a lot. I was trying to add a patch to the slack dev module and this solution helped.