Search code examples
phptry-catchslimflash-message

Slim flash messages not working inside try {} catch() {}


I'm working with the PHP Slim Framework in the version 2.6.1 (due to some limitation to upgrade PHP no a newer version) and when trying to use flash messages inside of a try/catch block the messages are not stored in the session when the template is rendered.

For example, the code below works fine (when the validator get some error the page is redirected with the desired flash messages):

$objValidation = FormValidator::isValidData($post);

if($objValidation->bolHasError)
{
   $app->flash('objValidation', serialize($objValidation));
   $app->flash('selectedData', $post);
   return $app->redirect('/app/edit/form/components/');
}

But if I start using a try block, like below, then the flash message is not stored in the $_SESSION (or even in the {{ flash }} in templates):

try {
    $objValidation = FormValidator::isValidData($post);

    if($objValidation->bolHasError)
    {
       $app->flash('objValidation', serialize($objValidation));
       $app->flash('selectedData', $post);
       return $app->redirect('/app/edit/form/components/');
    }

    # some other stuff processed here...
}
catch(Exception $e) {
    # do something
}

P.S.: the sessions are stored in the PHP native way ( session_start() ).

There are any limitations of scope for using the flash messages in that way?


Solution

  • I've figured out that the try block create a "isolated scope". So, I tried to to put a return false before the redirect to test if the in next page the flash message would show up. And finally the flash message was stored in the $_SESSION variable (of course the redirection was not executed, but at least I've discovered that the issue is related with the try scope).

    Then, the solution I found was to raise an exception and do the redirect inside the catch block. Like this:

    $objValidation = FormValidator::isValidData($post);
    
    if($objValidation->bolHasError)
    {
        throw new Exception('validation_error');
    }
    

    and then capture the error into the catch block:

    catch(Exception $e)
    {
        if($e->getMessage() == 'validation_error')
        {
            $app->flash('objValidation', serialize($objValidation));
            $app->flash('formData', $post);
    
            return $app->redirect('/api/form/change/components/');
        }
    }
    

    In that way I was able to get the flash message into template.