PHP Simple Auto Load

Just wanna share my PHP autoload function.
In my application, I have several types of classes and may located in different folder such as :
  • Helper
  • Model
  • Component
  • Web Service
  • etc
The easiest way to use the classes is to create an auto load function so the classes file will be included automatically.

Hope this could be useful to you too.
<?php
/**
 * Auto function
 * @param <string> $classname class name
 * @return <void> void
 */
function __autoload($classname) {
    global $global_helper_path;
    global $global_model_path;
    global $global_component_path;
    global $global_wsobject_path;

    //load helper
    $pos = strrpos($classname, "Helper");
    if ($pos === false) { // note: three equal signs
    } else {
        //print $classname;
        $filepath = "$global_helper_path/$classname.php";
        require_once "$filepath";
        return;
    }

    // load component
    $pos = strrpos($classname, "com_");
    if ($pos === false) { // note: three equal signs
    } elseif ($pos == 0) {
        $filepath = "$global_component_path/$classname/$classname.php";
        require_once "$filepath";
        return;
    }

    // load database driver
    $pos = strrpos($classname, "DB");
    if ($pos === false) { // note: three equal signs
    } elseif ($pos == 0) {
        $filepath = "$global_helper_path/database/$classname.php";
        require_once "$filepath";
        return;
    }

    // load model
    $pos = strrpos($classname, "Model");
    if ($pos === false) { // note: three equal signs
    } else {
        $filepath = "$global_model_path/$classname.php";
        require_once "$filepath";
        return;
    }

    // load webservice class
    $pos = strrpos($classname, "WS");
    if ($pos === false) { // note: three equal signs
    } elseif ($pos == 0) {
        $filepath = "$global_wsobject_path/$classname.php";
        require_once "$filepath";
        return;
    }
}

?>

0 comments:

 
Copyright © peyotest