Messages framework

Categories

Component ID

2825153

Component name

Messages framework

Component type

module

Maintenance status

Development status

Component security advisory coverage

not-covered

Component created

Component changed

Component body

Messages framework

This Drupal8 module enhances the standard Drupal messages functions drupal_set_message and drupal_get_messages giving you an OOP interface to these functions.

Using the messages functions directly is pretty ugly and does not follow the OOP approach. Moreover, it makes the code less testable, as it's more difficult to mock these function calls instead of mocking an object using Mockery or other object mocking frameworks.

This module exposes a service named messages_framework.messages that you can inject in your classes or services:

my_module.my_service:
  class: Drupalmy_moduleServiceMyService
  arguments:
    - '@logger.factory'
    - '@cache.default'
    - '@http_client'
    - '@config.factory'
    - '@messages_framework.messages' # messages framework injection

Then in you service class:


use Drupalmessages_frameworkServiceMessages;

class MyOtherServiceClass {
  /**
    * @var Messages
    */
  private $messages;

  function __construct(Messages $messages) {
    $this->messages = $messages;
  }
}

Or you can simply get the service using the Drupal global facade, if you are working on a .module file for example:

$messages = Drupal::service('messages_framework.messages')

Then accessing to the get and set methods is as easy as calling:

$messages->set('My message')

and

$all_messages = $messages->get()

Both functions accept the same parameters accepted by drupal_set_message and drupal_get_messages, so it's perfectly ok to call, for example:

$messages->set('My message', 'error')

to set an error messages.