Flash Messages

Install

Via Composer

  1. $ composer require slim/flash

Requires Slim 3.0.0 or newer.

Usage

  1. // Start PHP session
  2. session_start(); //by default requires session storage
  3. $app = new \Slim\App();
  4. // Fetch DI Container
  5. $container = $app->getContainer();
  6. // Register provider
  7. $container['flash'] = function () {
  8. return new \Slim\Flash\Messages();
  9. };
  10. $app->get('/foo', function ($req, $res, $args) {
  11. // Set flash message for next request
  12. $this->flash->addMessage('Test', 'This is a message');
  13. // Redirect
  14. return $res->withStatus(302)->withHeader('Location', '/bar');
  15. });
  16. $app->get('/bar', function ($req, $res, $args) {
  17. // Add message to be used in current request
  18. $this->flash->addMessageNow('Test', 'This is another message');
  19. // Get flash messages from previous request
  20. $messages = $this->flash->getMessages();
  21. // Returns both flash messages
  22. print_r($messages);
  23. });
  24. $app->run();

Please note that a message could be a string, object or array. Please check what your storage can handle.