How to handle status messages in an MVC-based website?
It's clear that you should be us开发者_如何学运维ing exceptions to handle errors in your app. But should you really use the incorporated messages to show them to the actual user?
If so, you'd have to internationalize those messages which is still manageable. But what about simple status information like "file successfully stored"? Those are not errors, obviously, so you can't use exceptions for them. How would you handle those?
I don't like the thought of having to deal with them for each area individually, but would prefer a global, unified way to handle error and simple status messages that will be shown to the user. What's the best way to do that? On the template level maybe? Is that the right place?
How about an event system, where the lowest severity/level/type would be a notice and the highest a fatal error? Is that feasible?
I use a FlashMessage
class for this purpose. It stores the message in a session and displays on the next page load. This way you can have a space in all your templates for displaying messages and if there is one set it will be displayed. You can then redirect and POST onto any page and the message will be displayed.
I personally do that on the template level.
For example...
Controller:
if(UsersModel::addNewUser($username)){
$this->set("user_added", true);
}
In the template:
<?
if(!empty($user_added)){
?>
<p>User added successfully!</p>
<?
}
?>
No problems with i18n (using gettext) here too and Controller stays clear:
if(!empty($user_added)){
?>
<p><?=_("User added successfully!");?></p>
<?
}
精彩评论