NYCPHP Meetup

NYPHP.org

[nycphp-talk] php autoloading

Paul M Jones pmjones88 at gmail.com
Fri Jan 16 12:06:16 EST 2009


On Jan 12, 2009, at 11:13 , Paul A Houle wrote:

>    I've recently written a "framework" that's part of a planned  
> software product line.  One of the consequences is that I've written  
> command-line PHP scripts that need to deal with objects that didn't  
> exist when the script was written,  so I needed an autoloader.
>
>   I did some research and I was really impressed with A.J. Brown's  
> dynamic autoloader:
>
> http://ajbrown.org/blog/2008/12/02/an-auto-loader-using-php-tokenizer.html
>
>   Rather than assuming a certain convention for how file names  
> relate to class names,  it scans directory trees,  parses files and  
> creates a mapping.  This adds some overhead,  but that can be  
> reduced by using serialize() to cache the result.  I've written some  
> thought about this up:
>
> http://gen5.info/q/2009/01/09/an-awesome-autoloader-for-php/
>
>   Any thoughts?

At the risk of sounding flippant, you could "[assume] a certain  
convention for how file names relate to class names" and use six lines  
of code for autoloading.  The PEAR naming convention is perfect for  
this.  Underscores in class names map to subdirectories, so the  
transformation of class name to file path is trivial.

     spl_autoload_register('houle_autoload');
     function houle_autoload($class)
     {
         $file = str_replace('_', '/', $class) . '.php';
         return $file;
     }

As a bonus, you then have a standard organizational structure for  
classes that works for everything everywhere the same way every time.



-- 

Paul M. Jones
http://paul-m-jones.com/







More information about the talk mailing list