Composer of automatic loading mechanism

Composer of automatic loading mechanism

ComposerProviding four automatic loading mode, respectively PSR-0, PSR-4generating classmapand comprising between files.

PSR-0 mode

PSR-0Approach requires the directory name and namespace layers of correspondence, this has led to a deep directory structure, it has now been officially abandoned. However, because now the mainstream PHPframework have been achieved PSR-0way, it Composeris still backward compatible. According to PSR-0the rules, when the load User\Infowhen the class, it will look for src/User/Info.php, and finally this configuration will be Mapin the form of written generated vendor/composer/autoload_namespaces.phpin.

"autoload": {
    "psr-0": {
        "User\\": "src/",
    }
}

PSR-4 mode

PSR-4When the way Composerrecommend a way to use, but also the PSR-0alternative. PSR-4Easier to use and has a simpler directory structure. When loaded automatically User/Infowhen the class, it will look for src/User/Infothe file. Configuration PSR-4 may be converted to namespaceto Key, DIR PATHto Valuethe Mapform, and writes the generated vendor/composer/autoload_namesapce.phpin.

"autoload": {
    "psr-4": {
        "User\\": "src/",
    }
}

classmap way

classmapWay through the configuration specified directory or file, then composer installor updatewhen. Scans in the specified directory .phpor .incfile to map specifies the class file path, and writes the generated vendor/composer/autoload_classmap.phpfile. Assumptions: srcnext there is a BaseControllerclass, then the autoload_classmap.phpfile, such a configuration will be generated: BaseController => $baseDir . '/src/BaseController.php'.

"autoload": {
    "classmap": ["src/", "lib/", "Something.php"]
}

files the way

filesManual mode is designated for direct file loaded. For example: There is a global helperfunction, it can be placed in a helperfile directly loaded. It generates an array that contains the configuration specified files, and then writes the resultingvendor/autoload_files.php

"autoload": {
    "files": ["src/app/helper.php"]
}

At last

In the configuration composer.jsonAfter completion, directly run composer install. Then at the entrance of the project file, the introduction require 'vendor/autoload.php'will be happy to use the relevant library.

Guess you like

Origin www.cnblogs.com/yxhblogs/p/11332542.html