views:

99

answers:

6

I have a custom class that, when called, will redirect to a page and send a 'message_type' and 'message' variable via GET. When the page opens it checks for these variables and displays a 'success', 'warning', or 'error' message depending on the 'message_type' variable. I made it so the user thinks they stay on the same page. It also allows for other variables to be passed along with the message.

Is this good practice, or should I just start using exceptions?

Example:

//Call a static function that will redirect to a page, with an error message
RedirectWithMessage::go('somepage.php', MessageType::ERROR, 'Error message here.');

The following checkMessage() function is an include file:

function checkMessage()
{
    if((isset($_GET['message_type']) && strlen($_GET['message_type'])) && (isset($_GET['message']) && strlen($_GET['message_type'])))
    {
        DisplayMessage::display($_GET['message_type'], $_GET['message']);
        return true;
    }
    return false;
}

On the page that is redirected to, call checkMessage();

//If a message is received, display it. If not, do nothing
checkMessage();

I know this might be vague, and I can supply more code if necessary. I guess the issue is that I don't have much experience using exceptions, but I think they seem cumbersome (writing try-catch blocks everywhere). Please let me know if I am making this more difficult for myself or if there is a better solution.

Thanks! Mike

+1  A: 

I think it's a good way to do it, I do something very similar, although I store the relevant error info in their session ($_SESSION) instead, and clear it right after it's displayed. That keeps it out of the query string, and makes it so if they refresh the page the error goes away

Michael Mrozek
Thanks Michael. I like the idea of storing the message in a $_SESSION variable. I have not liked the fact that the message remains when the page is refreshed.
letseatfood
A: 

I'm not sure if Exceptions and Try / Catch blocks are the way to go, but you may be able to build your success or error messages in the same page without having to redirect to another page.

Also, this adjustment to your IF condition is a bit easier to read and should achieve the same results:

if(!empty($_GET['message_type']) && !empty($_GET['message']))
brandon k
I was reading that empty() is not the most reliable way to check if a variable contains information. But you are correct in that it is easier to read. I just switched it to your version for now. Thanks!
letseatfood
A: 

I use the 'if' check a lot, because I never understood the try/catch process. I like the idea of putting the error in $_SESSION as well.

Drazisil
A: 

One thing is that it looks like your business logic might be tied to the PHP pages it is being run in, and so if you wanted to reuse some of it in a different context you might stuggle, as you would be stuck with having it redirect to a specific page on error.

If you used exceptions you would have the choice of trapping that error immediately and continuing, or letting it be handled higher up (e.g. giving up and showing an error page to the user).

Tom Haigh
Thanks Tom. I am not sure I follow exactly. Would you describe what it is that is tied to the PHP pages that the code runs in?
letseatfood
@Mike:I mean that if you tried to use it in a different project or something, you might struggle, as all the error handling is hard coded to make the user jump to another specific page. but that might not be an issue in your case. it was just a thought i had.
Tom Haigh
Gotcha, thanks!!
letseatfood
A: 

Store all messages as in array in Session. this class might be help you about how to make this http://flourishlib.com/browser/fMessaging.php

Osman Üngür
+1  A: 

Errors and exceptions are not totally the same. Exceptions are errors that are "exceptional" circumstances like unable to connect to database, unable to link to an external resource or perhaps a user entry that you deem to be an exception which causes application to halt.

Given that, using exceptions, you can implement error bubbling in your models/business objects and simply catch the error as high up in the call stack (Ideally in the controller or main page if your not using MVC pattern). If you want to throw the message directly, that's fine, but you might want to just use error codes so you can simply create an object or array of errors with their respective messages or even support localization or message variants of the same error. Once you have caught the error as an exception, you can then buffer it to a variable and simply display it in the template or view or do a redirect to a common message page.

<?php
  class SampleModel
  {
      public function validate($params)
      {
           if (!is_array($params)) {
                 throw new Exception("Input provided is not valid");
           }
           //add as many validations as you want.
           return TRUE;
      }  
  }
 ?> 

Usage:

<?php
      $model = new SampleModel();
      $input = "not an array"; 
      $msg = null;       
      $msgtype = null; 
      try {       
          $result = $model->validate($input); //this will throw a user-defined exception because we are passing a string instead of an array
          if ($result) {
              $msgtype = "success"; 
              $msg = "Successful validation";
          }

      } catch(Exception $e) {
          $msg = $e->getMessage();
          $msgtype = "Fatal error";  
      }

      RedirectWithMessage::go('somepage.php', $msgtype, $msg);

If you don't absolutely need to redirect, just load a different set of page template for is type of error.

      //load the appropriate template/view class. You need to create this class or use a framework.
      LoadWithMessage::display('sometemplate.inc.php', $msgtype, $msg); 

The sample code above is typically a controller.

Also, there's a performance overhead for $_SESSION not to mention additional latency once you go distributed (if your expecting your application to be big). I really would not advice using it for error messages. I'd typically just use it for data persistence. Error messages are not meant to persist and the web is stateless in nature.

walkthroughthecloud
Wow! Thank-you. I thought there was more to this. I'll have to look at this in the morning.
letseatfood