PHP
  Home arrow PHP arrow Page 2 - Improving Exception Throwing when Auto Loading Classes in PHP 5
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? 
PHP

Improving Exception Throwing when Auto Loading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2007-12-18


    Table of Contents:
  • Improving Exception Throwing when Auto Loading Classes in PHP 5
  • One Step Backward
  • Improving the Definition
  • The Improved Source Code

  • 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


    Improving Exception Throwing when Auto Loading Classes in PHP 5 - One Step Backward
    ( Page 2 of 4 )

    Going one step backward: throwing exceptions with the “__autoload()” function independently of a “try-catch()” block

    Before I proceed to teach you how to throw exceptions from inside the corresponding “__autoload()” function, which can then be intercepted correctly by a “try-catch()” block, I’d like to list the full source code of the example I developed in the preceding tutorial of this series, where this functionality wasn’t implemented yet.

    In doing so, it’ll be much easier for you to grasp the small changes that I’m going to introduce to the definition of the “__autoload()” magic function, which will provide it with the capacity to launch the aforementioned exceptions.

    All right, having said that, please take a close look at the following code sample, which implements a basic exception mechanism within the pertinent “__autoload()” function:


    (definition of mysql.php file)


    class MySQL{

    private $host;

    private $user;

    private $password;

    private $database;

    private $connId;

    // constructor

    function __construct($options=array()){

    if(!is_array($options)){

    throw new Exception('Connection options must be an array');

    }

    foreach($options as $option=>$value){

    if(empty($option)){

    throw new Exception('Connection parameter cannot be empty');

    }

    $this->{$option}=$value;

    }

    $this->connectDb();

    }

    // private 'connectDb()' method

    private function connectDb(){

    if(!$this->connId=mysql_connect($this->host,$this->user,$this->password)){

    throw new Exception('Error connecting to MySQL');

    }

    if(!mysql_select_db($this->database,$this->connId)){

    throw new Exception('Error selecting database');

    }

    }

    // public 'query()' method

    public function query($sql){

    if(!$result=mysql_query($sql)){

    throw new Exception('Error running query '.$sql.' '.mysql_error());

    }

    return new Result($this,$result);

    }

    }



    (definition of result.php file)


    class Result{

    private $mysql;

    private $result;

    // constructor

    public function __construct($mysql,$result){

    $this->mysql=$mysql;

    $this->result=$result;

    }

    // public 'fetch()' method

    public function fetch(){

    return mysql_fetch_array($this->result,MYSQL_ASSOC);

    }

    // public 'count()' method

    public function count(){

    if(!$rows=mysql_num_rows($this->result)){

    throw new Exception('Error counting rows');

    }

    return $rows;

    }

    // public 'get_insertId()' method

    public function getInsertId(){

    if(!$insId=mysql_insert_id($this->mysql->connId)){

    throw new Exception('Error getting insert ID');

    }

    return $insId;

    }

    // public 'seek()' method

    public function seek($row){

    if(!int($row)&&$row<0){

    throw new Exception('Invalid row parameter');

    }

    if(!$row=mysql_data_seek($this->mysql->connId,$row)){

    throw new Exception('Error seeking row');

    }

    return $row;

    }

    // public 'getAffectedRows()' method

    public function getAffectedRows(){

    if(!$rows=mysql_affected_rows($this->mysql->connId)){

    throw new Exception('Error counting affected rows');

    }

    return $rows;

    }

    }



    (definition of autoload_example.php file)


     

    try{

    function __autoload($className){

    if(!file_exists($className.'.php')){

    eval("class $className {}");

    throw new Exception('Class not found');

    }

    require_once $className.'.php';

    }

    // connect to MySQL

    $db=new MySQL(array
    ('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'database'));

    // fetch users from database table

    $result=$db->query('SELECT * FROM users ORDER BY id');

    // display user data

    while($row=$result->fetch()){

    echo 'Id: '.$row['id'].' First Name: '.$row['firstname'].' Last Name: '.$row
    ['lastname'].' Email: '.$row['email'].'<br />';

    }

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    As you’ll probably recall, the previous hands-on example implements a basic database-driven application that is given the task of fetching some basic data on a few fictional users from a simple MySQL table, which are then displayed on the browser. In addition, I concretely implemented the “__autoload()” function at the beginning of this example so it can be used to include the respective “MySQL” and “Result” classes required by this application in the client code (keep in mind that these reside on different PHP files).

    Now that you've hopefully recalled how the previous database-driven application does its business, suppose that for any reason the file that contains the pertinent “MySQL” class has been removed from the file system.

    Based on this hypothetical and certainly conflictive scenario, when the “autoload_example.php” file is parsed by the PHP 5 interpreter, it will complain loudly because this class simply won’t be available and consequently, the following fatal error will be triggered:


    Fatal error: Function __autoload(MySQL) threw an exception of type 'Exception' in path/to/file


    Much better, but not very elegant, right? In this case, the “__autoload()” function implements a simple workaround that allows it to throw an exception when trying to include the missing “MySQL” class, even when it can’t be properly caught inside the corresponding “try-catch()” block.

    Obviously, from a programmer’s point of view, throwing exceptions that can’t be intercepted by one “try-catch()” block is pointless. In this case, it’s necessary to introduce some additional improvements to the definition of the “__autoload()” magic function, so it can be provided with the capacity to launch exceptions that can be trapped within a “try-catch()” structure.

    Bearing in mind that this issue needs to be fixed quickly, in the upcoming section I’m going to slightly modify the signature of the “__autoload()” function to implement the aforementioned feature.

    To see how these changes will be incorporated into this handy function, please click on the link below and keep reading.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





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