Let's say, we want to integrate Error-Handling in our application, but we don't know yet, if we want the error to be display, logged in a file, stored to the database, or all of the above. Our goal is, to keep the object that raises the error independent of the objects that store the error message.
classMyErrorextendsJObservable{public$msg=NULL;functionraiseError($msg){$this->msg=$msg;//Notify all attached ErrorHandlers of the state change.$this->notify();}}//We now implement the Observers, thus the error handlersclassErrorHandlerDisplayextendsJObserver{functionupdate(){echo$this->subject->msg;}}classErrorHandlerFileStorageextendsJObserver{functionupdate(){error_log($this->subject->msg;);}}classErrorHandlerDBextendsJObserver{functionupdate(){$db=JFactory::getDBO();$sql="INSERT INTO #__myerrors (message) VALUES (".$db->quote($this->subject->msg).")";$db->setQuery($sql);$db->query();}}//Now we can use newly implemented MyError class to raise Errors.$error=newMyError();/* The constructor of the observers automatically attaches the observer to the subject * In our example that means that the constructor of the error handler automatically * attaches the handler to the MyError Object. */newErrorHandlerDisplay($error);newErrorHandlerFileStorate($error);newErrorHandlerDB($error);$error->raiseError('Help!!!');/* * Would cause 'Help!!!' to be display, logged in a file, and stored in the database. * You can simply add and remove the error handlers as you like */
What happened here? We separated the functionality of raising an error of the functionality of handling an error. In the future you can add additional ErrorHandlers, or remove some of the existing handlers, without the need to change any classes at all. Furthermore you can simply change an Errorhandler, without the need to change the MyError class. This greatly increases the reusability of your code.
This example was originally provided by Batch1211.
Let's say, we want to integrate Error-Handling in our application, but we don't know yet, if we want the error to be display, logged in a file, stored to the database, or all of the above. Our goal is, to keep the object that raises the error independent of the objects that store the error message.
What happened here? We separated the functionality of raising an error of the functionality of handling an error. In the future you can add additional ErrorHandlers, or remove some of the existing handlers, without the need to change any classes at all. Furthermore you can simply change an Errorhandler, without the need to change the MyError class. This greatly increases the reusability of your code.
This example was originally provided by Batch1211.