Best Practice to return user information
Every time it bothers me; how to return information (login success, article updated)back to the user especially in OOP.. (PHP)
- throw new exception with multiple catch and try blocks (after catch it will stop the execution of the catch block)
- just a bunch return values (just looks awful)
- true and false (then in the script where you run the class check for true and false?)
- separated class to handle the error messages (extends Exceptions?)
Any tips would be appreciated!
— Update / not axpecting so many answers! wow!!
For example user registration; I used a custom exception class.
/*
* custom exception class
*/
class Message extends Exception
{
public function __construct($message, $code = true)
{
parent::__construct($message, $code);
}
public function information()
{
return '<div class="check"><img src="/admin/static/images/'.($this->code == true ? 'good' : 'bad').'.gif" alt="check" class="icon" width="20px" height="20px" />' . $this->message . '</div>';
}
}
and in the class itself;
if(is_numeric($id) === false)
{
Throw new Message('message', false);
}
Exceptions can be costly also exceptions normally denote a problem with the app itself like a cURL error, not something as simple as just the user making a mistake or not logging in right. I would keep exceptions to actual problems in your app and report only to you on them.
Depends on how you do these returns values. Look into how PHP frameworks do it like:
In particular ( a nice way of doing this ) is Yii’s own login handler for users: http://www.yiiframework.com/doc/api/1.1/CUserIdentity
You will notice they have class based error codes and messages.
You will find a lot of these frameworks use a model/controller based pattern for forms which means you define a set of validation rules (even for logging in a user, as in Yii many times the auth is class based) and these validation rules run filling up error messages attached to these rules. Eventually you have an array like:
Which denotes all your return values. It is nice and tidy since it is per field errors and they are also easy to get to and manipulate in a loop.
For actually logging in a user many times you would run something along the lines of:
And the return of this would normally be something like what was shown above for forms.
True and false are very vague when it comes to multiple errors, for example:- the user logs in but their account can be deleted or banned. How would you tell the difference by just boolean?
Other people/frameworks like Lithium (for example) return boolean per validation function which is then attached to a error message holder.
As many others say the path comes down to your particular situation.