LionsAd / service_container

Service Container Module on drupal.org - used for development and automated testing via travis

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use Session from HttpFoundation to store messages from Messenger.

drupol opened this issue · comments

I'm putting this code here as a reminder. Here's a quick working example of a Messenger using Session from HttpFoundation.
There's a thread on d.o. about it, I can't find it anymore, maybe @dawehner will help.

<?php

/**
 * @file
 * Contains \Drupal\service_container\Messenger.
 */

namespace Drupal\service_container\Messenger;

use Drupal\service_container\Legacy\Drupal7;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * Class that manage the messages in Drupal.
 */
class Messenger implements MessengerInterface {

  /**
   * The Drupal 7 legacy service.
   *
   * @var \Drupal\service_container\Legacy\Drupal7
   */
  protected $drupal7;

  /**
   * The Session service.
   *
   * @var \Symfony\Component\HttpFoundation\Session\Session;
   */
  protected $session;

  /**
   * Constructs a Messenger object.
   *
   * @param \Drupal\service_container\Legacy\Drupal7 $drupal7_service
   *    The Drupal 7 legacy service.
   * @param \Symfony\Component\HttpFoundation\Session\Session $session
   *    The Session service.
   */
  public function __construct(Drupal7 $drupal7_service, SessionInterface $session) {
    $this->drupal7 = $drupal7_service;
    $this->session = $session;
  }

  /**
   * {@inheritdoc}
   */
  public function addMessage($message, $type = self::STATUS, $repeat = FALSE) {
    $this->session->getFlashBag()->add($type, $message);
    return $this->session->getFlashBag()->peekAll();
  }

  /**
   * {@inheritdoc}
   */
  public function getMessages() {
    return $this->session->getFlashBag()->peekAll();
  }

  /**
   * {@inheritdoc}
   */
  public function getMessagesByType($type) {
    return $this->session->getFlashBag()->peek($type);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMessages() {
    $this->session->getFlashBag()->clear();
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMessagesByType($type) {
    $this->session->getFlashBag()->get($type);
  }
}

There's nothing much left to do to get this working in D7. Ex: We could use a block to display the messages.

That is a won't-fix, we don't gain anything from mixing in the session component here.

As it is not integrated with the rest of Drupal.

The important thing is that we have the interface (that hopefully Drupal 8 will also use from 8.1.x on).

Yes I was looking for the thread about it. But anyway, this is just a code example on how to use it, as a reminder if we need it somewhere.