PHP
  Home arrow PHP arrow Page 4 - 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 - Event Logging
    ( Page 4 of 4 )

    Event logging is exactly what the name suggests – the recording of events in an application. Logging is most often associated with error logging and authentication logging, but can be used for a much wider array of problems. Logging can be used to track visitor statistics, form submissions, and database activities. Logging can even be used to catalog script execution step by step in a meaningful way that allows developers to review a detailed execution path with relevant data to isolate script problems. In most applications, error logging and authentication logging are the extent of what is needed, but be creative and use logs to your advantage when trying to solve more complex problems.

    Storing our log files presents the same general decisions as choosing how to store our application data. I prefer logging to a database to simplify the collection of statistical data. There is a problem with that approach though – can you guess? What happens when our application cannot access the database used for logging?

    This is where flat file logging comes in handy. When writing code to handle logging to a database, it is wise to always code your logging tool to switch over to a flat file when a database is not available. Consider the following extremely basic logging class.

    <?php
    class Log
    {
     var $settings;
     var $dbh;
     var $method;

     function Log(&$settings, &$dbh)
     {
      $this->settings = &$settings;
      $this->dbh = &$dbh;
      $this->method = ‘db’;

      if (gettype($this->dbh) != ‘resource’)
      {
       $this->dbh = mysql_connect($settings[‘db’][‘host’],
                     $settings[‘db’][‘user’],
                     $settings[‘db’][‘pass’]);
      } 

      if (gettype($this->dbh) != ‘resource’)
      {
       $this->method = ‘file’;
      }
     } 

     function record($message)
    {
     switch ($this->method)
     {
      case ‘file’ :
    return $this->recordToFile($message);
       break;
      case ‘db’ :
       return $this->recordToDb($message);
       break;  
     }
    }
    }
    ?>

    You can use your imagination for the “recordToFile” and “recordToDb” methods, as the intent is clear. Obviously the object would need to know the name of the file to which log messages should be appended; we can accomplish this by storing the path to the log file in settings or by telling the log explicitly where to write. We can also extend this class to log in different formats or even use subclassing to determine which logfiles are written to.

    You can also use your imagination to tangle up the “Error” and “Log” classes discussed above in all sorts of ways. The following example shows a basic way to configure the error object with a logging object. The example will also demonstrate the use of multiple debugging levels to determine what information is logged. Assume all class and configuration code from above is available to this script. There are a couple of new methods on the error handler here, but the usage is obvious and I will not define the code for those methods.

    <?php
    define(‘DEBUG_LEVEL’, 1);

    require_once(‘class.log.php’);
    $log = &new Log(&$settings, NULL);

    if (DEBUG_LEVEL > 0)
    {
     $log->record(‘PID ‘.getmypid().’ Started’);
    }

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

    if (DEBUG_LEVEL > 0)
    {
     $log->record(‘Trying database connection’);
    }

    $dbh = @mysql_connect($settings[‘db’][‘host’],
            $settings[‘db’][‘user’],
            $settings[‘db’][‘pass’]);

    if (gettype($dbh) != ‘resource’)
    {
     trigger_error(‘Unable to connect to database’);
    }
    elseif (DEBUG_LEVEL > 0)
    {
     $log->record(‘Database connection established’);
    }


    if (DEBUG_LEVEL > 0)
    {
     $log->record(‘PID ‘.getmypid().’ Ended’);
    }

    ?>

    In this example, setting “DEBUG_LEVEL” to 0 causes the script to only record catastrophic errors, whereas setting it to 1 will cause the script to record every action taken. In a situation where our task was performed by another object, we would want to be sure that the object knew as little about the error object as possible – basically the “setError” method. This allows us to pass any subclass of the error object to our class without changing code in the dependant class.

    Like many of the practices discussed thus far, the most important thing about logging is that you use it. Logging is an invaluable tool for maintaining an application. It is the only method by which detailed application information can be captured transparently and stored for later review. This information can, when provided in sufficient detail and context, provide a conceptual window through which to view a system problem.

    A quick note – you probably noticed that I did not choose to use a database abstraction layer in my example code. There are a few reasons for this, the first of which is brevity. I do not care to delve into which layer is the best and how they work. Next, most PHP applications do not need a database abstraction layer. It is not the norm for PHP applications to require portability to other databases, and even though the need does exist at times we should use classes judiciously and avoid them when they are not needed.

    Finally, I want to preempt the common argument that an abstraction layer enforces uniform access methods throughout code. Anyone familiar with ADODB or PEAR::DB knows full well that these packages are a mess and allow you to interact with a database in a variety of methods, each inconsistent with the other in theory and implementation. While these layers have their usage, they do not belong in most Web applications. Adhering to conventions and writing clean code will solve for uniformity, with or without an abstraction layer.

    Conclusion

    This article has covered some important fundamentals for PHP application development. Building on what we discussed in part one, we examined data storage, system configuration, error handling and logging. Though the exploration of each was brief, the overall purpose of each was clear. Practicing the use of these concepts greatly simplifies application maintenance and testing and, if used properly, it can accelerate system debugging radically.

    My implementations are not necessarily “the” way to practice these concepts, they are simply the way I have learned through experience and study to handle them. I encourage you with this, as with any new idea, to poke and prod at it and form your own opinions. The article is intentionally light on code to facilitate this. If you analyze the problem and form your own solutions using the contents of this article as a sort of guide, you will find a solution to most any problem these concepts can solve.

    In the next article we will discuss some basic database planning considerations and naming conventions for databases and discuss user authentication and management. See you then!



     
     
    >>> 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 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek