Alex Rivera | Logout

Where should we store confirmation/error messages in application?

Asked 2011-05-31T07:03:24.360
10

I am working on PHP and Zend. I have to show different type of error/confirmation messages in application. Most of these messages are placed in code. So if I have to change one message then I have to change it everywhere where this particular type of message is coded.

So what is the best way to store all messages in on place and use them across the application.

Possible solutions:

  • Store all messages in database. (We have to move these messages to other database type. For example if we move from MySQL to SQL Server.)

  • Store all messages in separate php class using array and get these messages using class methods (Problem: We can not use this class in other programming languages.)

  • Store message in special format which acceptable for all languages for example ini type of files.

EDIT: (After looking Ozair's Answer)

Sometimes we have to change message for particular record. For example:

Product No. 10 is deleted.
Product No. 15 is deleted.

What will be best method to handle this case ?

Thanks

Edit
Report

1 Answer

2

How about storing it in some non-direct coding language and then use a macro for transforming this into an array or static class or whatever you like? It may be in the database, XML or whatever you'd like. You would only need 2 fields for an error message: the name of the message and the content.

For example, in XML you might do this:

<messages>
  <message>
    <name>PRODUCT_SAVED_OK</name>
    <content>Product no. %d has been saved successfully</content>
  </message>
  ...
</messages>

Then have some process to transform this into arrays or the thing that best fits your project. For example, I would save this to an array:

$messages = array(
  'PRODUCT_SAVED_OK' => 'Product no. %d has been saved successfully',
  ...
);

And for dealing with variables inside the messages, I'd do printfs:

if ($saved_ok)
{
  printf($messages['PRODUCT_SAVED_OK'], $product_number);
}

Of course, encapsulate this inside a Message class for better and cleaner code. One drawback of the printf solution is that you need to know in advance which parameters do any message need. If you'd like to translate the message and some message with more than one parameter gets them inverted in another language, printf can deal with this:

// In both cases, day would be 3rd parameter to printf, month the second and year the first
$spanish = 'Hoy es %3$d/%2$d/%1$d';
$english = 'Today is %2$d/%3$d/%1$d';
answered 2011-05-31T08:24:34.553

Your Answer