Slim Framework flash messages service provider

Overview

Slim Framework Flash Messages

Build Status

This repository contains a Slim Framework Flash messages service provider. This enables you to define transient messages that persist only from the current request to the next request.

Install

Via Composer

$ composer require slim/flash

Requires Slim 3.0.0 or newer.

Usage

Slim 4

This example assumes that you have php-di/php-di installed.

<?php

use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Flash\Messages;
use Slim\Routing\RouteContext;

require_once __DIR__ . '/../vendor/autoload.php';

$containerBuilder = new ContainerBuilder();

// Add container definition for the flash component
$containerBuilder->addDefinitions(
    [
        'flash' => function () {
            $storage = [];
            return new Messages($storage);
        }
    ]
);

AppFactory::setContainer($containerBuilder->build());

$app = AppFactory::create();

// Add session start middleware
$app->add(
    function ($request, $next) {
        // Start PHP session
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        // Change flash message storage
        $this->get('flash')->__construct($_SESSION);

        return $next->handle($request);
    }
);

$app->addErrorMiddleware(true, true, true);

// Add routes
$app->get(
    '/',
    function ($request, $response) {
        // Set flash message for next request
        $this->get('flash')->addMessage('Test', 'This is a message');

        // Redirect
        $url = RouteContext::fromRequest($request)->getRouteParser()->urlFor('bar');

        return $response->withStatus(302)->withHeader('Location', $url);
    }
);

$app->get(
    '/bar',
    function ($request, $response) {
        $flash = $this->get('flash');

        // Get flash messages from previous request
        $messages = $flash->getMessages();
        print_r($messages);

        // Get the first message from a specific key
        $test = $flash->getFirstMessage('Test');
        print_r($test);

        return $response;
    }
)->setName('bar');

$app->run();

Slim 3

// Start PHP session
session_start();

$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();

// Register provider
$container['flash'] = function () {
    return new \Slim\Flash\Messages();
};

$app->get('/foo', function ($req, $res, $args) {
    // Set flash message for next request
    $this->flash->addMessage('Test', 'This is a message');

    // Redirect
    return $res->withStatus(302)->withHeader('Location', '/bar');
});

$app->get('/bar', function ($req, $res, $args) {
    // Get flash messages from previous request
    $messages = $this->flash->getMessages();
    print_r($messages);

    // Get the first message from a specific key
    $test = $this->flash->getFirstMessage('Test');
    print_r($test);
});

$app->run();

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

Using with Twig-View

If you use Twig-View, then slim-twig-flash may be a useful integration package.

Testing

$ phpunit

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Flashing arrays

    Flashing arrays

    I have a situation where I'd like to be able to flash the POST data from the previous request. As I see it, the only way to do this right now would be to loop through the POST data and add each value as a separate key.

    I'd really like to be able to, instead, simply pass in the parsed body of the request as an array and have all the array stored under one key.

    So, instead of having to do something like:

    $data = $request->getParsedBody();
    foreach($data as $key=>$value) {
        $messages->addMessage($key,$value); 
    }
    

    I feel like it much better to be able to do this:

    $data = $request->getParsedBody();
    $messages->addMessage('old_input',$data);
    

    It seems to me that this would be an easy, and non-breaking change. Unless I'm mistaken, something as simple as changing the Messages::addMessage method like this should do it:

    public function addMessage($key, $message)
        {
            //Check if message is an array, and just use it if it is
            if(is_array($message)) {
                $this->storage[$this->storageKey][$key] = $message;        
                return;
            }
            //Create Array for this key
            if (!isset($this->storage[$this->storageKey][$key])) {
                $this->storage[$this->storageKey][$key] = array();
            }
            //Push onto the array
            $this->storage[$this->storageKey][$key][] = (string)$message;
        }
    

    Another option would be to add a separate method for adding the request body as a message, but I don't know if that would be necessary.

    Is this doable? I'd be happy to submit a pull request for it, but before I do I'm curious to know if this is acceptable, and if there are any reasons that this couldn't be done. I'd think that this would be a pretty common requirement so having a straightforward and quick way to do this would be great.

    Thanks, -A

    enhancement 
    opened by adear11 13
  • Adds a TwigExtension to access flash messages within a Twig template

    Adds a TwigExtension to access flash messages within a Twig template

    opened by NigelGreenway 10
  • Passing string, returns it inside array

    Passing string, returns it inside array

    @geggleto said he will fix what he broke šŸ’ƒ

    https://github.com/slimphp/Slim-Flash/commit/5bd5f75eac27433beeccd60d2777b4e58da84834#diff-8b1b6164c747942bdb2576f146cf4e5eR87

    opened by dopesong 7
  • Show messages on twig without reload / redirecting

    Show messages on twig without reload / redirecting

    I have a view with a form, i want show the flash messages if my form validation got fail, the problem is when showing messages to my view, the messages just showed when the page is reloaded , or when redirecting to other routes/view ...

    opened by mai92 5
  • "Flash messages middleware failed. Session not found" when using default Slim test runner

    Hi, I set up my application using the skeleton here: https://github.com/slimphp/Slim-Skeleton

    Specifically I'm using this test runner to exercise controllers: https://github.com/slimphp/Slim-Skeleton/blob/master/tests/Functional/BaseTestCase.php

    I defined a controller that says $this->flash->addMessage('Error', 'Invalid phone number')

    I get the following stack trace:

    Slim Application Error:
    Type: RuntimeException
    Message: Flash messages middleware failed. Session not found.
    File: /Users/kevin/code/callyo-10-21-commander/vendor/slim/flash/src/Messages.php
    Line: 62
    Trace: #0 /Users/kevin/code/callyo-10-21-commander/web/src/dependencies.php(37): Slim\Flash\Messages->__construct()
    #1 /Users/kevin/code/callyo-10-21-commander/vendor/pimple/pimple/src/Pimple/Container.php(113): Tests\Functional\BaseTestCase->{closure}(Object(Slim\Container))
    #2 /Users/kevin/code/callyo-10-21-commander/vendor/slim/slim/Slim/Container.php(123): Pimple\Container->offsetGet('flash')
    #3 /Users/kevin/code/callyo-10-21-commander/vendor/slim/slim/Slim/Container.php(172): Slim\Container->get('flash')
    #4 /Users/kevin/code/callyo-10-21-commander/web/src/controllers/GroupsController.php(34): Slim\Container->__get('flash')
    #5 [internal function]: Commander\Controllers\GroupsController->getList(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
    #6 /Users/kevin/code/callyo-10-21-commander/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php(41): call_user_func(Array, Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
    #7 /Users/kevin/code/callyo-10-21-commander/vendor/slim/slim/Slim/Route.php(344): Slim\Handlers\Strategies\RequestResponse->__invoke(Array, Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
    #8 /Users/kevin/code/callyo-10-21-commander/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(116): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
    #9 /Users/kevin/code/callyo-10-21-commander/vendor/slim/slim/Slim/Route.php(316): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
    

    Not sure whether the error is in Slim's test runner or here, but it seems like this should work without blowing up.

    It's also worth considering whether the default should be to fail silently instead of loudly.

    opened by kevinburke 4
  • Adding Key support and Key Array support to flash messages

    Adding Key support and Key Array support to flash messages

    In my apps, I find having different keys to store flash messages a critical component. Being able to flag [warn] or [error] messages for rendering in my UI is pretty critical. This PR attempts to add this functionality.

    opened by geggleto 4
  • Add a message to the current request's stack

    Add a message to the current request's stack

    As addMessage(), but adds to the current stack fromPrevious, to use messages in the current request (immediately).

    Sees usage in my project for generating a form failure notice before rendering the output, in the same request.

    opened by bartbrinkman 3
  • Persisting across redirects

    Persisting across redirects

    Hello,

    In some cases, I can have multiple redirections in my app; wich will cause my flash messages to be lost. Back to Slim2, I got the same problem I was able to solve using the flashKeep() method.

    Right now, I'm able to retrieve it by manually getting message, and settign them back again with addMessage; but that only works for one level redirection, I can have two :/

    How should I resolve this? Is there a way to get kind of flashKeep() behaviour?

    Thank you :)

    opened by trasher 2
  • Passing arrays not working propably

    Passing arrays not working propably

    I'm experiencing an issue where an array is not passed probably via flash messages.

    I followed the setup from the README, further setup:

    // First request
    $this->flash->addMessage('inputs', ['test' => 'input']);
    
    // Second request
    var_dump($this->flash->getMessages()['inputs'][0]); // => string(5) "Array"
    
    opened by timwattenberg 2
  • Possible to allow html tags?

    Possible to allow html tags?

    Hello,

    Is it possible to allow HTML tags? For `example:

    $this->flash->addMessage('global', 'You have an issue at <strong>this field</strong>!'
    

    It outputs without the <strong> markup. The message contains literal:

    You have an issue at <strong>this field</strong>!
    

    Instead of:

    You have an issue at this field!

    opened by matthijs110 2
  • Is we dont need to clear the message?

    Is we dont need to clear the message?

    Just want to know about this flash messages,

    I have create some test with this library and this is working fine,

    but I can not get the message twice, actualy i didn't clear the message.

    then i check the message with hasMessage('test') function and the result is null.

    Is we dont need to clear the message? is it already cleared as default? or this is a bug?

    Where is the session gone?

    Thanks.

    opened by aalfiann 1
  • Problems with ArrayAccess storage

    Problems with ArrayAccess storage

    When using an ArrayAccess storage (I'm using adbario/slim-secure-session-middleware) the addMessage fails to write the message to the storage. The problem is that with ArrayAccess double indexing cannot be used:

    $this->storage[$this->storageKey][$key] = array();

    has no effect. Instead the following should be used:

    $temp = $this->storage[$this->storageKey];
    $temp[$key] = array();
    $this->storage[$this->storageKey] =$temp;
    
    

    I made a small modification to addMessage which seems to work:

    public function addMessage($key, $message)
        {
           // Workaround for ArrayAccess storage
            $temp = $this->storage[$this->storageKey];
            // Create Array for this key
            if (!isset($temp[$key])) {
                $temp[$key] = [];
            }
            // Push onto the array
            $temp[$key][] = $message;
            $this->storage[$this->storageKey] = $temp;
        }
    
    opened by sverlan 1
  • Returning message(s) stored for next request

    Returning message(s) stored for next request

    We have getMessages() which is returning from the previous request, and everything is a derivative of this. I want messages to be sent to the next request, but also retrieve them within the current logic I am doing prior to that for validation or otherwise.

    I would need to be accessing $this->storage[$this->storageKey] to get anything currently stored for the next request.

    Please let me know whether it's viable to add a new method to support this, or I am just being stupid and missing something overt that achieves what I'm aiming for.

    opened by pridit 2
Owner
Slim Framework
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Slim Framework
Slim Framework HTTP cache middleware and service provider

Slim Framework HTTP Cache This repository contains a Slim Framework HTTP cache middleware and service provider. Install Via Composer $ composer requir

Slim Framework 107 Dec 15, 2022
Symprowire is a PHP MVC Framework based and built on Symfony, using the ProcessWire CMS as DBAL and Service Provider.

Symprowire - PHP MVC Framework for ProcessWire 3.x Symprowire is a PHP MVC Framework based and built on Symfony using ProcessWire 3.x as DBAL and Serv

Luis Mendez 7 Jan 16, 2022
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Slim Framework Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs. Installation It's recommended

Slim Framework 11.5k Jan 4, 2023
Slim Framework - Prerequisite Checker

Slim Framework - Server Configuration Checker Upload the file check.php to your webserver Browse to the file: https://example.com/check.php Check the

Daniel Opitz 6 Aug 30, 2022
REST APIs using Slim framework. Implemented all CRUD operations on the MySql database

PHP REST API using slim framework and CRUD operations ?? Hi there, this is a simple REST API built using the Slim framework. And this is for the folks

Hanoak 2 Jun 1, 2022
A Slim PHP MVC framework built just for fun!

Aura Framework A Slim PHP MVC framework built just for fun! en: Note: This repository only contains the core code of the Aura framework. If you want t

Murilo MagalhĆ£es Barreto 2 Dec 16, 2021
Slim Framework skeleton application with MVC Schema

Slim Framework skeleton application with MVC Schema

JingwenTian 9 Apr 29, 2021
This repository contains a library of optional middleware for your Slim Framework application

Slim Framework Middleware This repository contains a library of optional middleware for your Slim Framework application. How to Install Update your co

Slim Framework 47 Nov 7, 2022
A curated list of awesome tutorials and other resources for the Slim micro framework

Awesome Slim A curated list of awesome tutorials and other resources for the Slim micro framework Table of Contents Essentials Tutorials Packages and

Sawyer Charles 466 Dec 8, 2022
Slim Framework 3 Skeleton Application + PagSeguro Lib

Slim Framework 3 Skeleton Application + PagSeguro Lib AplicaĆ§Ć£o simples para geraĆ§Ć£o do Token para pagamentos no PagSeguro (mĆ©todo transparente) e env

RaĆ­ Siqueira 1 Feb 26, 2018
My personal blog developed on the Slim Framework

nesbot.com I am making the source code of my personal site available publicly in case it helps anybody. It's developed using the Slim Framework. I am

Brian Nesbitt 56 Sep 14, 2022
Plates Template Integration for Slim micro framework 3

Plates Template Integration for Slim micro framework 3 Render your Slim 3 application views using Plates template engine. Install Via Composer $ compo

Projek XYZ 26 Feb 5, 2022
Juliangut Slim Framework Doctrine handler middleware

Juliangut Slim Framework Doctrine handler middleware Doctrine handler middleware for Slim Framework. Slim3 version Doctrine integration service for Sl

JuliƔn GutiƩrrez 6 Mar 23, 2021
This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library

This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library. It supports minification and caching, also via Asseti

Gerard Sychay 22 Mar 31, 2020
Strict PSR-7 implementation used by the Slim Framework

Strict PSR-7 implementation used by the Slim Framework, but you may use it separately with any framework compatible with the PSR-7 standard.

Slim Framework 96 Nov 14, 2022
Slim Framework custom views

Slim Views This repository contains custom View classes for the template frameworks listed below. You can use any of these custom View classes by eith

Slim Framework 302 Feb 21, 2022
Access control middleware for Slim framework

Slim Access Access control middleware for Slim framework. Supported formats IPv4 and IPv6 addresses CIDR notation all keyword Installation composer re

Alexandre Bouvier 7 Oct 22, 2019
Redis cache middleware for Slim framework

RedisCache Redis cache middleware for Slim framework. Installation composer require abouvier/slim-redis-cache Usage Cache every successful HTTP respo

Alexandre Bouvier 16 Sep 20, 2021
Slim Framework using Jade for templates

Welcome to Slim-Jade What? This is a boilerplate. It's the Slim Framework with jade.php to render views Why? I like the Sinatra style MVC and love Jad

Joe Fleming 23 Oct 16, 2019