Re: autoload, include_once naming conventions

From: Date: Thu, 17 Mar 2005 21:42:02 +0000
Subject: Re: autoload, include_once naming conventions
References: 1  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-36727@lists.php.net to get a copy of this message
Lukas Smith wrote:
while talking with Derick about what we dont like about PHP5 in Budapest I got an idea ... Basically what if we would replace all (require|include)_once calls with a static PEAR method. This method would get a class name passed and would simply do an class_exists() call and if the class do include the code by replacing "_" to "/".
This sounds very much like what I'm doing with the Solar project (http://solarphp.com). You make the call like this: // will look for Some/Class/Name.php $obj = Solar::object('Some_Class_Name'); ... and that runs through these two static functions: public static function object($class, $config = null) {
    $result = Solar::autoload($class);
    if (Solar::isError($result)) {
        return $result;
    } else {
        $obj = new $class($config);
        return $obj;
    }
} // __autoload() does not work for static calls, // at least not the last time I tested it. public static function autoload($class) {
    // pre-empt searching for the class
    if (class_exists($class)) {
        return;
    }
    if (trim($class) == '') {
        return Solar::error(
            'Solar', // class
            'no_autoload_class', // code
            'no class named for autoload', // text
            array('class' => null), // info
            E_USER_ERROR // level
        );
    }
    // convert the class name to a file path.
    $file = str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
    // include the file.
    include_once $file;
    // if the class was not in the file, we have a problem.
    if (! class_exists($class)) {
        return Solar::error(
            'Solar', // class
            'class_not_found', // code
            'class not found in autoload file', // text
            array('class' => $class, 'file' => $file), // info
            E_USER_ERROR // level
        );
    }
} Feel free to use (or not ;-) as you wish. -- pmj

« previous php.pear.dev (#36727) next »