Reputation: 2024
for a new project I decided to renew my coding practices. The one thing that bothers me right now is the use of Exceptions. In the past I have used a custom class MyException which inherited the common Exception class and extended its functionality (basically I created a few new classes to format output, give debugging information, etc.):
class MyException extends Exception {
private $messages = array(
// ...
"NOT_LOGGED_IN" => 'Please login to use this API.',
"INVALID_LOGIN" => 'The login credentials you provided are invalid.',
"SESSION_TIMED_OUT" => 'Your session has timed out.',
"INVALID_SESSION" => 'Your login is invalid.',
// ...
);
public function __construct($id,$data=null) {
if($data == null)
return parent::__construct($this->messages[$id]);
return parent::__construct(call_user_func_array('sprintf',array_merge((array)$this->messages[$id],$data)));
}
}
So each time I threw an Exception I just called throw new MyException("INVALID_SESSION")
(or any other index of course). I feel like using this method might not be sufficient anymore for upcoming bigger and more professional projects. If I look at, for example, Java, I see that they define each Exception as a custom class which inherits the base class Exception. Also, in both Java and PHP I learned that there should only be one class in one file. This is logical for Java as it compiles to a binary but for PHP it would have to load and include all custom Exceptions each time the page is called and thus reduce performance (and there are probably going to be about a hundred and more Exceptions).
What is the best practice here?
Greetings
Upvotes: 2
Views: 417
Reputation: 713
PEAR2 has some good reccomendations about how to define and use exceptions. I recommend reading up on them: https://wiki.php.net/pear/rfc/pear2_exception_policy
PSR-0 defines an autoloading standard that will make instantiating these exceptions easier. I also recommend reading up on that standard: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
Upvotes: 1
Reputation: 437366
The best practice is to use as many exception classes as make sense, each in its own file, and utilize an autoloader to load those files on demand. This way you are only paying for the exceptions that get thrown.
Upvotes: 4