View Single Post
  #8 (permalink)  
Old 04-17-2008, 01:55 AM
Mark^Bastard Mark^Bastard is offline
Junior Member
 
Join Date: May 2007
Posts: 15
Default

Thanks, that code looks very interesting.

Last night I actually did something myself, completely different way though. I made my own loading class that extends Zend_Loader.

PHP Code:
<?php

class Lsdev_Loader extends Zend_Loader {

    public static function 
loadClass($class$dirs null)
    {
        if (
substr($class, -5) == 'Model') {
            
self::loadModel($class);
        }
        elseif (
substr($class, -4) == 'Form') {
            
self::loadForm($class);
        }
        else {
            
parent::loadClass($class$dirs);
        }
    }
    
    
    public static function 
loadModel($class)
    {
        
self::loadCustom($class'models');
    }
    
    public static function 
loadForm($class)
    {
        
self::loadCustom($class'forms');
    }
    
    public static function 
loadCustom($class$type)
    {
        
$basePath '../application';
        
        
$parts self::__explodeCase($class);

        switch (
count($parts)) {
            case 
:
                
parent::loadClass($class"$basePath/$type/");
                break;

            case 
:
                
parent::loadClass($class"$basePath/modules/{$parts[0]}/$type/");
                break;

            default :
                throw new 
Zend_Exception("Lsdev_Loader::loadCustom() Invalid class "
                                       
"name specified: <b>$class</b>");
                break;
        }
    }

    private static function 
__explodeCase($string$lower true)
    {
        
$array preg_split('/([A-Z][^A-Z]*)/'$string, -1PREG_SPLIT_NO_EMPTY PREG_SPLIT_DELIM_CAPTURE);
        if (
$lower) {
            
$array array_map('strtolower'$array);
        }
        return 
$array;
    }

    public static function 
autoload($class)
    {
        try {
            
self::loadClass($class);
            return 
$class;
        } catch (
Exception $e) {
            return 
false;
        }
    }
}
I register it with my boot strapper using the following code.

PHP Code:
// Enable autoloading of classes
include 'Zend/Loader.php';
Zend_Loader::registerAutoload('Lsdev_Loader'); 
Now I can autoload models and also forms very easily based on their name.

For example inside my IndexController I can do...

$news = new NewsModel();

It will automatically search for NewsModel.php in /application/models/

If I want to use modules, I can just add the module name to the start.

$news = new BlogNewsModel();

It will automatically search for BlogNewsModel.php in /application/modules/blog/models/

It's obviously based on camel casing. This is a working draft that could be improved upon by handling directories better.

Note I used camel casing so as not to conflict with Zend's use of underscores to match directories.

Interested in feedback.
Reply With Quote