超薄框架闪存和中间件

I'm learning how to use Slim Framework and I have a problem using flash message inside a custom middleware.

The problem is quite simple: I use the $app->flash('error', 'my message'); in the middleware and there is no message in the next page.

The middleware works great by the way

Here is my code:

Middleware

class SessionMiddleware extends \Slim\Middleware {

    public function call() {

        $app = $this->app;
        $req = $app->request;


        if(!preg_match('#^(/public)#', $req->getPath())) {
            if(isset($_SESSION['user']) && !empty($_SESSION['user'])) {
                //Do something
            } else {
                $app->flash('error', 'You must be logged');
                if($req->getPath() != '/login') {
                    $app->redirect('/login');
                }
            }
        }

        $this->next->call();

    }

}

Login

<?php
if(isset($_SESSION['slim.flash']['error'])) {
    echo '<p class="alert alert-danger"><strong>Error</strong>: '.$_SESSION['slim.flash']['error'].'</p>';
}
?>

App

$app = new \Slim\Slim(array(
  'mode' => 'development',
  'debug' => true,
  'templates.path' => './templates'
));

$app->add(new \SessionMiddleware());

$app->get('/login', function() use($app) {
  $app->render('login.php');
});

Any ideas how to fix that ?

Thank you

Try to use flashNow instead of flash method.

I also saw that 'flash' and 'flashNow' methods are not working in middleware. To add flash message, I decided to do it manually. It's working, but I know that's not the best approach.

$_SESSION['slim.flash']['error'] = 'message';

Running into this issue myself.

Since Flash is an app middleware component and is added by default, and before you add any custom app middleware components, it won't actually be initialised when your middleware is called.

Doing what @kkochanski has done is hacky, but is probably the only option, short of removing/unsetting Flash and adding it as the final app middleware component.

I'm facing with the same problem and resolve it. You can achieve that with call another method in authenticated route and flashing inside it for example

class AuthController
{
  public function flashError($request, $response)
  {
    // flash
    // redirect
  }
}

It works well for me. So you can just redirect to and make sure this method handle it. So you can flashing message outside middleware.