PHP
  Home arrow PHP arrow Page 4 - 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 - 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!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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 6 hosted by Hostway
    Stay green...Green IT