views:

29

answers:

1

Hi, so i got told in this question: http://stackoverflow.com/questions/2291413/php-javascript-passing-message-to-another-page

to use flash_set and flash_get, concept called "Rails flash".. Now can you use them in php those function? I can really find them in php library site, so im not sure..

A: 

You can store the messages you want to flash on the next page request in the $_SESSION. I don't know exactly how the methods work in rails but hopefully these two functions can be of use:

function flash_get()
{
    // If there are any messages in the queue
    if(isset($_SESSION['flashMessages']))
    {
        // Fetch the message queue
        $messages = $_SESSION['flashMessages'];

        // Empty out the message queue
        unset($_SESSION['flashMessages']);

        return $messages;
    }

    // No messages so just return an empty array
    return array();
}

function flash_set($message)
{
    // If the queue is currently empty we need to create an array
    if(!isset($_SESSION['flashMessages'])) {
        $_SESSION['flashMessages'] = array();
    }

    // Fetch the current list of messages and append the new one to the end
    $messages = $_SESSION['flashMessages'];
    $messages[] = $message;

    // Store the message queue back in the session
    $_SESSION['flashMessages'] = $messages;
}

Just call flash_set() with the message you want to store and flash_get() will give you that array back and flush the queue on a later page request.

You'll have to make sure as well that you call session_start() with every page request for these methods to work.

smack0007
But this is just like storing with normal session, but you did it to functions?
Karem
it's not quite that simple, as this won't distinguish between messages added on a previous page and those added earlier in the current page, you'll need to store 'current' and 'previous' separately, and on page-load, swap them over. Zend Framework's FlashMessenger might be helpful to look at.
Greg
This by no means a complete solution, it's 2 short methods. I use the Zend Framework version as well but since he never mentioned anything about a framework I didn't feel it was necessary to suggest he use one just to get some simple functionality.
smack0007
@Azzyh Yes, it's just storing some strings in the session, but instead of copying and pasting the 5 lines of code everywhere you can just call the functions. As far as I know, there is no build in way to do this. As Greg mentioned though, Zend Framework has a solution for this problem which is much better then the 2 functions I presented. If you want to work with a framework, you might consider that.
smack0007