PHP
  Home arrow PHP arrow Page 3 - PHP Application Development Part Two
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

PHP Application Development Part Two
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek