Best Way To Autoload Classes In PHP

前端 未结 6 659
陌清茗
陌清茗 2020-12-05 10:20

I\'m working on a project whereby I have the following file structure:

index.php
|---lib
|--|lib|type|class_name.php
|--|lib|size|example_class.php


        
相关标签:
6条回答
  • 2020-12-05 10:53

    Please, if you need to autoload classes - use the namespaces and class names conventions with SPL autoload, it will save your time for refactoring. And of course, you will need to instantiate every class as an object. Thank you.

    Like in this thread: PHP Autoloading in Namespaces

    But if you want a complex workaround, please take a look at Symfony's autoload class: https://github.com/symfony/ClassLoader/blob/master/ClassLoader.php

    Or like this (I did it in one of my projects):

    <?
    spl_autoload_register(function($className)
    {
        $namespace=str_replace("\\","/",__NAMESPACE__);
        $className=str_replace("\\","/",$className);
        $class=CORE_PATH."/classes/".(empty($namespace)?"":$namespace."/")."{$className}.class.php";
        include_once($class);
    });
    ?>
    

    and then you can instantiate your class like this:

    <?
    $example=new NS1\NS2\ExampleClass($exampleConstructParam);
    ?>
    

    and this is your class (found in /NS1/NS2/ExampleClass.class.php):

    <?
    namespace NS1\NS2
    {
        class Symbols extends \DB\Table
        {
            public function __construct($param)
            {
                echo "hello!";
            }
        }
    }
    ?>
    
    0 讨论(0)
  • 2020-12-05 10:56

    You can specify a namespaces-friendly autoloading using this autoloader.

    <?php
    spl_autoload_register(function($className) {
        $file = __DIR__ . '\\' . $className . '.php';
        $file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
        if (file_exists($file)) {
            include $file;
        }
    });
    

    Make sure that you specify the class file's location corretly.

    Source

    0 讨论(0)
  • 2020-12-05 10:59

    http://php.net/manual/de/function.spl-autoload-register.php

    spl_autoload_register(function ($class) {
        @require_once('lib/type/' . $class . '.php');   
        @require_once('lib/size/' . $class . '.php');
    });
    
    0 讨论(0)
  • 2020-12-05 11:00

    I have an example here that I use for autoloading and initiliazing.
    Basically a better version of spl_autoload_register since it only tries to require the class file whenever you initializes the class.
    Here it automatically gets every file inside your class folder, requires the files and initializes it. All you have to do, is name the class the same as the file.
    index.php

    <?php
    require_once __DIR__ . '/app/autoload.php';
    
    $loader = new Loader(false);
    
    User::dump(['hello' => 'test']);
    

    autoload.php

    <?php
    class Loader 
    {
    
        public static $library;
    
        protected static $classPath = __DIR__ . "/classes/";
    
        protected static $interfacePath = __DIR__ . "/classes/interfaces/";
    
        public function __construct($requireInterface = true) 
        {
            if(!isset(static::$library)) {
                // Get all files inside the class folder
                foreach(array_map('basename', glob(static::$classPath . "*.php", GLOB_BRACE)) as $classExt) {
                    // Make sure the class is not already declared
                    if(!in_array($classExt, get_declared_classes())) {
                        // Get rid of php extension easily without pathinfo
                        $classNoExt = substr($classExt, 0, -4); 
                        $file = static::$path . $classExt;
    
                        if($requireInterface) {
                            // Get interface file
                            $interface = static::$interfacePath . $classExt;
                            // Check if interface file exists
                            if(!file_exists($interface)) {
                                // Throw exception
                                die("Unable to load interface file: " . $interface);
                            }
    
                            // Require interface
                            require_once $interface;
                            //Check if interface is set
                            if(!interface_exists("Interface" . $classNoExt)) {
                                // Throw exception
                                die("Unable to find interface: " . $interface);
                            }
                        }
    
                        // Require class
                        require_once $file;
                        // Check if class file exists
                        if(class_exists($classNoExt)) {
                            // Set class        // class.container.php
                            static::$library[$classNoExt] = new $classNoExt();
                        } else {
                            // Throw error
                            die("Unable to load class: " . $classNoExt);
                        }
    
                    }
                }
            }
        }
    
        /*public function get($class) 
        {
            return (in_array($class, get_declared_classes()) ? static::$library[$class] : die("Class <b>{$class}</b> doesn't exist."));
        }*/
    }
    

    You can easily manage with a bit of coding, to require classes in different folders too.
    Hopefully this can be of some use to you.

    0 讨论(0)
  • 2020-12-05 11:07

    If you have an access to the command line, you can try it with composer in the classMap section with something like this:

    {
        "autoload": {
            "classmap": ["yourpath/", "anotherpath/"]
        }
    }
    

    then you have a wordpress plugin to enable composer in the wordpress cli : http://wordpress.org/plugins/composer/

    0 讨论(0)
  • 2020-12-05 11:12
    function __autoload($class_name) {
       $class_name = strtolower($class_name);
       $path       = "{$class_name}.php";
       if (file_exists($path)) {
           require_once($path);
       } else {
           die("The file {$class_name}.php could not be found!");
       }
    }
    

    UPDATE: __autoload() is deprecated as of PHP 7.2

    0 讨论(0)
提交回复
热议问题