Composer of automatic loading mechanism
Composer
Providing four automatic loading mode, respectively PSR-0
, PSR-4
generating classmap
and comprising between files
.
PSR-0 mode
PSR-0
Approach 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 PHP
framework have been achieved PSR-0
way, it Composer
is still backward compatible. According to PSR-0
the rules, when the load User\Info
when the class, it will look for src/User/Info.php
, and finally this configuration will be Map
in the form of written generated vendor/composer/autoload_namespaces.php
in.
"autoload": {
"psr-0": {
"User\\": "src/",
}
}
PSR-4 mode
PSR-4
When the way Composer
recommend a way to use, but also the PSR-0
alternative. PSR-4
Easier to use and has a simpler directory structure. When loaded automatically User/Info
when the class, it will look for src/User/Info
the file. Configuration PSR-4 may be converted to namespace
to Key
, DIR PATH
to Value
the Map
form, and writes the generated vendor/composer/autoload_namesapce.php
in.
"autoload": {
"psr-4": {
"User\\": "src/",
}
}
classmap way
classmap
Way through the configuration specified directory or file, then composer install
or update
when. Scans in the specified directory .php
or .inc
file to map specifies the class file path, and writes the generated vendor/composer/autoload_classmap.php
file. Assumptions: src
next there is a BaseController
class, then the autoload_classmap.php
file, such a configuration will be generated: BaseController => $baseDir . '/src/BaseController.php'
.
"autoload": {
"classmap": ["src/", "lib/", "Something.php"]
}
files the way
files
Manual mode is designated for direct file loaded. For example: There is a global helper
function, it can be placed in a helper
file 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.json
After 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.