PHP
  Home arrow PHP arrow Page 3 - PHP Application Development Part Two
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

PHP Application Development Part Two
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 33
    2005-03-08

    Table of Contents:
  • PHP Application Development Part Two
  • Storing Dynamic Data
  • Error Handling
  • Event Logging

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    PHP Application Development Part Two - Error Handling


    (Page 3 of 4 )



    Error handling is the next subject for discussion. Error handling is a topic that could (and does) fill an entire book, but for our purposes we only need to understand the fundamentals. Error handling should be “graceful” in any system – meaning that the application should know how to detect its own errors and handle them in some appropriate manner with minimal interruption for end users. In PHP, error handling is something that developers tend to overcomplicate. There is a tendency to use elaborate error handling classes that store far more information than is needed and not the information that is really needed. The following example demonstrates a simple error class.

    <?php
    class Error
    {
     var $number;
     var $string;
     var $file;
     var $line;

     function setError($number, $string, $file, $line)
     {
      $this->number = $number;
      $this->string = $string;
      $this->file = $file;
      $this->line = $line;

      $this->showError();
     }

    function showError()
    {
     print ‘Error (‘.$this->code.’): ‘.$this->message.”<br />
    ”.$this->file.’ (‘.$this->line.’)<br />’;
    }
    }
    ?>

    This very simple class takes in the error data via the “setError” function and spits the data back out via “showError.” The two methods are chained together. While this class is not especially useful for handling errors gracefully, it is the foundation for capturing the errors after attempts at a graceful recovery have failed and for acting upon the information provided by the error. Task-specific error handling is best left for the actual scripts or classes performing the task.

    Implementing this class as our error handler in PHP is simple. See the following example.

    <?php
    $errorHandler = &new Error();
    set_error_handler(array(&$errorHandler, ‘setError’));
    ?>

    This will send any error in the script to “$errorHandler”. Consider the following sample, where the script will attempt to recover from a failed database connection by iterating over a set of possible databases. Data from the configuration file that would be used in this situation is inserted into the file directly. Assume that “class.error.php” contains our error class and is available in the default include path.

    <?php
    $settings[‘db’][0][‘user’] = ‘someuser’;
    $settings[‘db’][0][‘pass’] = ‘password’;
    $settings[‘db’][0][‘host’] = ‘192.168.1.2’;
    $settings[‘db’][0][‘name’] = ‘MyApp’;

    $settings[‘db’][1][‘user’] = ‘root’;
    $settings[‘db’][1][‘pass’] = ‘password’;
    $settings[‘db’][1][‘host’] = ‘192.168.1.120’;
    $settings[‘db’][1][‘name’] = ‘MyApp’;


    $settings[‘db’][2][‘user’] = ‘root’;
    $settings[‘db’][2][‘pass’] = ‘’;
    $settings[‘db’][2][‘host’] = ‘localhost’;
    $settings[‘db’][2][‘name’] = ‘MyApp’;

    require_once(‘class.error.php’);
    $errorHandler = &new Error();
    set_error_handler(array(&$errorHandler, ‘setError’));

    $dbh = false;
    $try = 0;
    do
    {
     $dbh = @mysql_connect($settings[‘db’][$try][‘host’],
           $settings[‘db’][$try][‘user’],
            $settings[‘db’][$try][‘pass’]);
    } while (($dbh === false) && ($try < count($settings[‘db’])));

    if ($dbh === false)
    {
     trigger_error(‘Unable to connect to database.’, E_USER_ERROR);
    }
    ?>

    In this example we have two available hosts that attempt to establish a database connection with “mysql_connect” one host at a time until a connection is established. This is a type of error recovery – our application is provided with alternate possible databases to try connecting to before failing. If no connection can be made, we will pass a fatal error notice to our error handler.

    Typically just a warning would be generated from a failed MySQL connection, but since our example application is dependent on one, the script needs to halt. A more elaborate configuration could involve the error handler being configured with objects to delegate errors to, in this case perhaps some top level object that handles stopping a script and presenting a user with the appropriate message. We could also extend our Error class and delegate certain types of errors or errors that match certain keywords to the appropriate subclass.

    In PHP 5, error handling is even more powerful with exceptions and try/catch structures, allowing developers to specialize error handling on a per-object or even per-task basis, maximizing the usefulness of the data provided by the exceptions. Since this article is meant to be general and the example above also works in PHP 5, we will not have an exceptions example, though the principles are still the same.

    Error handling is a pretty broad subject and the example above only chips the iceberg. Ultimately, error handling becomes very narrow in the context of a particular task, and in those cases you as a developer must use your experience and your problem solving skills to determine what options are available for handling the error, and how to handle it as succinctly and effectively as possible.

    One of the most important uses of error handling in a live application is to capture real errors generated by real use of the system. This allows developers to work with live data, often in ways they did not predict during initial testing. There is a problem, though; how do developers know what error data is going through their application? One word: logging.

    More PHP Articles
    More By David Fells


       · Just wanted to say i am really enjoying these articles. Keep it up.. I am a self...
       · PHP5 has a robust built-in error handling in the form of exceptions. Also the object...
       · I totally agree that an upgrade to PHP 5 is the way to go, unfortunately that's not...
       · If you don't have the money to get your own server (or if your IT department won't...
       · Really enjoying the articles. I have been developing in PHP for about 4 years now...
       · Hi David,A nice couple of articles. I'm looking forward to the next one in this...
       · woops =) proofreading never was my strong suit =)
       · Hi! Im looking forward for your next article.
       · I am waiting for your next article. Thanks for your effort and experience
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT