Implementation of Automatic Loading in Project Practice of [PHP]

Time:2019-9-10

1. Register a self-defined autoload function using the spl_autoload_register function
2. When a new non-existent class is in the code, the above function is called and the non-existent class name is passed into the function as a parameter.
3. Compatible with two ways, namespace corresponds to directory app test, class name underline divides corresponding directory app_test, all of which are test.php files under the corresponding app directory, and the class name should be the same as the file name.
4. set_include_path(), which can have multiple colons: separate, dynamically set the include_path configuration options in php.ini

 

libPath = (($path), DIRECTORY_SEPARATOR);
        ($this->getLibPath());
        if ($autoload) {
            spl_autoload_register(array('Application', 'load'));
        }
        return $this;
    }
    public static function instance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    // Get the file suffix
    public function getPhpExt() {
        return $this->phpExt;
    }
    // Setting File Suffixes
    public function setPhpExt($ext) {
        $this->phpExt = $ext;
        return $this;
    }
    // Setting the root path
    public function setPath($path) {
        $this->path = (($path), DIRECTORY_SEPARATOR);
        return $this;
    }
    // Setting the path of automatic loading
    public function getLibPath() {
        return $this->path . DIRECTORY_SEPARATOR . $this->libPath;
    }
    // Automatic Loading Function
    public static function load($class) {
        $pos = ($class, '\');
        if ($pos !== false) {
            $ns = ('\', DIRECTORY_SEPARATOR, ($class, 0, $pos + 1));
            $className = ($class, $pos + 1);
        } else {
            $ns = DIRECTORY_SEPARATOR;
            $className = $class;
        }
        if (($className, '_') !== false) {
            $className = ('_', DIRECTORY_SEPARATOR, $className);
        }        
        $ins = self::instance();
        $classFile = $ins->getLibPath() . $ns . $className . $ins->getPhpExt();
        if (!(include $classFile)) {
            throw new Exception('load class failed: class=' . $class . ' file=' . $classFile);
        }
    }
}
Application::instance()->setPath((__FILE__))->setLibPath(DIRECTORY_SEPARATOR, true);
// Test, create the app directory in the root directory, and create these two files below
new app_user();
new \app\admin();

User.php under app directory

<?php class app_user{
    public function __construct(){
        new \app\admin();
    }
}

Admin.php in app directory

<?php namespace app;
class admin{}