Giter Site home page Giter Site logo

slim-flash's Introduction

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.

slim-flash's People

Contributors

acinader avatar akrabat avatar bcremer avatar codeguy avatar designermonkey avatar geggleto avatar joebengalen avatar l0gicgate avatar odan avatar rickycheers avatar silentworks avatar tflight avatar thinksalot avatar timwattenberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slim-flash's Issues

Render HTML Tags

I usually use HTML Tags in success or error messages, to display something important e.g. username which has been deleted or something.

However slim\flash doesn't render the HTML. Message I'm getting: User <b>rene</b> has been deleted.

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

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 ...

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!

Ability to clear messages in 'queue'

It can be useful to clear the queued messages:

    public function clearMessages() : void {
        if (isset($this->storage[$this->storageKey])) {
            $this->storage[$this->storageKey] = [];
        }
    }

    public function clearMessage(string $key) : void {
        if (isset($this->storage[$this->storageKey][$key])) {
            unset($this->storage[$this->storageKey][$key]);
        }
    }

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"

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.

Flash messages for the current request

In Slim 2.x (which, admittedly, I never used!) it seems like it was possible to add a message to the current request, before the template was rendered, with the flashNow method.

Is this possible now, or are there plans to make this an option again?

Thanks!

Default value to getMessage()

Have you thought about adding a second parameter to getMessage() to allow for overriding the default 'null' value in case the key does not exist?

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.

Used Model/View

I would like to know how to use Slim / Flash in class in an application using Model/View I must inject depencias in every class that I need?

New method: setMessage

I have a suggestion: wouldn't be useful to have a method that just sets a flash message without adding to an array? For instance if we have an array of validation errors. It would work like this:

// setting
flash->setMessage('errors', [...])

// retrieving
$errors = flash->getMessage('errors');
// send the errors to the template

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 :)

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;
    }

Get the first message

Very often you would only need one message of a certain key ; or you know 100% there is only one. If that is the case its mega overhead to be doing array looping/checking in your display code.

Can we introduce something like this?

class V6Messages extends \Slim\Flash\Messages {
    public function getFirstMessage($key) {
        $messages = self::getMessage($key);
        if(is_array($messages) && count($messages)>0) {
            return $messages[0];
        }

        return null;
    }
}

After that you can just use

{{$messages->getFirstMessage('key')}}

in your template code nice and clean.

"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.

Customisable flash key

Please allow a customisable key in the constructor. This allows us to have multiple flash groups, errors and warnings for example.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.