Skip to content

Instantly share code, notes, and snippets.

@frodosghost
Forked from BaylorRae/flash_messages.php
Created May 23, 2011 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frodosghost/986645 to your computer and use it in GitHub Desktop.
Save frodosghost/986645 to your computer and use it in GitHub Desktop.
Flash Messages for PHP
<?php
/**
* Usage Examples
*/
$flash_message = FlashMessage::getInstance();
$flash_message->set('notice', 'This is a notice message');
$flash_message->flash('This is a flash message');
?>
<?php if ($flash_message->has('notice')) : ?>
<div class="flash_notice"><?php echo $flash_message->get('notice')?></div>
<?php endif ?>
<?php
/**
* Simple interface for dealing with flash messages
*/
class FlashMessage
{
private $messages = array();
private static $instance = null;
/**
* Only allows one instance of the class
*
* @return FlashMessage
*/
public static function getInstance()
{
if(self::$instance === null)
{
self::$instance = new FlashMessage();
}
return self::$instance;
}
/**
* Constructor
*/
public function __construct()
{
$this->messages = $_SESSION['messages'];
}
/**
* Allows simple message adding
*
* @param String $name
* @param Array $args
*/
public function __call($name, $args)
{
$this->set($name, $args[0]);
}
/**
* Set Message
*
* @param String $name
* @param String $message
*/
public function set($name, $message)
{
$this->messages[$name] = $message;
$this->save();
}
/**
* Return a Message
*
* @param String $name
* @return String
*/
public function get($name)
{
return $this->has($name) ? $this->messages[$name] : null;
}
/**
* Checks if the class has the variable set
*
* @param String $name
* @return Boolean
*/
public function has($name)
{
return array_key_exists($name, $this->messages);
}
/**
* Destroys messages in session
*/
public function destroy()
{
unset($_SESSION['messages']);
}
/**
* Saves messages into session
*/
public function save()
{
$_SESSION['messages'] = $this->messages;
}
}
?>
@BaylorRae
Copy link

On line #64 you could use your has() method.

return $this->has($name) ? $this->messages[$name] : null;

@frodosghost
Copy link
Author

Great idea. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment