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:

  1. class MessageStack {
  2. var $_stack = array();
  3. /**
  4. * Factory function, ensures that
  5. * MessageStack is a singleton
  6. */
  7. function create() {
  8. }
  9. function add($type, $text) {
  10. $this->_stack[$type][] = $text;
  11. }
  12. /**
  13. * Returns stack contents
  14. */
  15. function get() {
  16. return $this->_stack;
  17. }
  18. }

When I want to report something I call:

  1. $messageStack = MessageStack::create();
  2. $messageStack->add(‘ok’, ‘Record saved.’);

Then in your main file you run this:

  1. $messageStack = MessageStack::create();
  2. $smarty->assign("messages", $messageStack->get());

Include this into template (preferably the part that is included into every template):

  1. {foreach from=$messages key=type item=messagesType}
  2. {section name=pc loop=$messagesType}
  3. <div class="message {$type}">{$messagesType[pc]}</div>
  4. {/section}
  5. {/foreach}

And then in css, define all message types:

  1. .message {
  2. font-weight: bold;
  3. padding: 5px;
  4. }
  5. .critical {
  6. background-color: black;
  7. padding: 2px 5px 3px 5px;
  8. margin: 3px 0px;
  9. }

Question

Do you use something like this or something more clever? Share your wisdom :-)

Leave a Reply