How to report messages to user
In the course of executing a program you need to report errors / success messages to the user. But you don’t want to mix your code with HTML, right? (A quick explanation on separating presentation from business / data logic.)
So here’s what I use:
-
class MessageStack {
-
…
-
/**
-
* Factory function, ensures that
-
* MessageStack is a singleton
-
*/
-
function create() {
-
…
-
}
-
function add($type, $text) {
-
$this->_stack[$type][] = $text;
-
}
-
/**
-
* Returns stack contents
-
*/
-
function get() {
-
return $this->_stack;
-
}
-
}
When I want to report something I call:
-
$messageStack = MessageStack::create();
-
$messageStack->add(‘ok’, ‘Record saved.’);
Then in your main file you run this:
-
$messageStack = MessageStack::create();
-
$smarty->assign("messages", $messageStack->get());
Include this into template (preferably the part that is included into every template):
-
<div class="message {$type}">{$messagesType[pc]}</div>
-
{/section}
-
{/foreach}
And then in css, define all message types:
-
.message {
-
font-weight: bold;
-
padding: 5px;
-
}
-
.critical {
-
background-color: black;
-
padding: 2px 5px 3px 5px;
-
margin: 3px 0px;
-
}
Question
Do you use something like this or something more clever? Share your wisdom :-)