As I mentioned before, my purpose here is to modify the signature of the "Result" class by providing it with the ability to throw specific exceptions when processing MySQL data sets. Based on this idea, the pertinent "Result" class would now look as follows: // redefine 'Result' class class Result { private $mysql; private $result; public function __construct($mysql,$result){ $this->mysql=$mysql; $this->result=$result; } // fetch row public function fetchRow(){ if(!$row=mysql_fetch_assoc($this->result)){ return false; } return $row; } // count rows public function countRows(){ if(!$rows=mysql_num_rows($this->result)){ throw new ResultException('Error counting rows'); } return $rows; } // count affected rows public function countAffectedRows(){ if(!$rows=mysql_affected_rows($this->mysql->conId)){ throw new ResultException('Error counting affected rows'); } return $rows; } // get ID of last-inserted row public function getInsertID(){ if(!$id=mysql_insert_id($this->mysql->conId)){ throw new ResultException('Error getting ID'); } return $id; } // seek row public function seekRow($row=0){ if(!is_int($row)||$row<0){ throw new ResultException('Invalid result set offset'); } if(!mysql_data_seek($this->result,$row)){ throw new ResultException('Error seeking data'); } } } That wasn't rocket science, right? As you can see, the above "Result" class is now capable of throwing some customized exceptions of type "ResultException" each time an error occurs, either when counting and seeking rows in a result set, or when retrieving the ID of an insertion, update or deletion operation. Of course, these same failures could have been handled through generic exceptions. In this case, however, I want to provide you with a simple example to help you learn how to create classes that trigger customized exceptions. At this point, I've modified the signature of the previous "Result" class, which now will trigger a special type of exception when something goes wrong. The next step that must be taken consists of creating a subclass that handles these exceptions via a "try-catch" block. Building such a subclass will be the last topic that I plan to discuss in this article. If you're interested in learning how the class in question will be constructed, please click on the link below and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|