Sending UI Messages in PHP

I am using sessions to save UI messages that can be shown to the user after an action has been formed (ie: logging in).

My initial problem was that the message persisted, while attempts to unset the session message didn’t allow for any messages to be shown.

Here’s how I solved the problem:


class Application {
...
  public function getMessages() {
    $messages = $_SESSION['messages'];
    unset($_SESSION['messages']);
    return $messages;
  }
}

First save the messages from the session, then you can delete them out of the session so they don’t persist past the one request.

Here is how I set the proper success or error message in the login function:


public function doLogin($username, $password) {
  ...
  if ( $username == $user->username && $password == $user->password ) {
      $_SESSION['logged_in'] = true;
      $this->addMessage('You are now logged in.', 'success');
  } else {
     $_SESSION['logged_in'] = false;
      $this->addMessage('We were unable to log you in.', 'error');
  }

  return $this->isLoggedIn();
}

I’m using smarty templating for PHP; here is how I get messages into my layout template:


class Application {
  ...
  public function showPage() {
    ...
    $smarty->assign('messages', $this->getMessages());
  }
  ...
}
VN:F [1.8.4_1055]
Rating: 10.0/10 (1 vote cast)
VN:F [1.8.4_1055]
Rating: 0 (from 0 votes)
Sending UI Messages in PHP10.0101

Tags: , , ,

Leave a Reply