Hello, 3 days ago I started rewriting one of my scripts in OOP using classes as a practice after reading a lot about the advantages of using OOP.
Now I'm confused weather I should use exceptions or not. They seem to make my work harder and longer.
My application check if the data was sent through an Ajax request or not then uses that info through the script.
Check this example :
/*
* The older way
*/
if($ajaxEnabled) {
$error = errorWrap('Ajax error');
} else {
$error = errorWithBackLinkWrap('NoAjax error');
}
function doSomething() {
if(empty($POST['name'])) {
die($error);
}
}
/*
* OOP way
*/
class someClass {
private $_ajaxEnabled;
public function doSomething() {
try {
if(!$this->_isDateValid()) {
if($this->$_ajaxEnabled) {
throw new ajaxException('Ajax error');
} else {
throw new noAjaxException('NOAjaxError');
}
}
} catch(ajaxException $e) {
echo $e->getErrorMessage();
} catch(noAjaxException $e) {
echo $e->getErrorMessage();
}
}
}
This code is only for demonstrating the problem, so I know there are some undefined functions in it :).
So before going oop, error handling was easier for me because I only had to echo the appropriate error.
Now using exceptions, in every function I have to check the type of connection first then write 2 catch functions for each thrown exception, which lead to a much larger code.
I'm really new to OOP in php so maybe there is a cleaner and a better way to do this, is there ?