For automatic loading of a third party package, Composer provides support of four ways, namely PSR-0 and autoloaders PSR-4 generates class-map, and the files contained directly.
First introduced autoload.php
, in the main index.php file.
require 'vendor/autoload.php';
PSR-4 (recommended)
In composer.json is carried out in the configuration:
{ "autoload": { "psr-4": { "Foo\\": "src/" } } }
Perform composer install
updates automatically load, update execution Composer dump-the autoload . According to the rules of the PSR-4, when trying to index.php new Foo\Bar\Baz
when this class, composer will automatically look for "src / Bar / Baz.php" this file, if it exists, is loaded.
PSR-0 (not recommended)
In composer.json is carried out in the configuration:
{ "autoload": { "psr-0": { "Foo\\": "src/" } } }
Perform composer install
updates automatically load, update execution Composer dump-the autoload . Note that according to the rules PSR-0 when trying to index.php new Foo\Bar\Baz
when this class, composer will look for "src / Foo / Bar / Baz.php " this file, if it exists, is loaded.
NOTE: Also note PSR-4 and is disposed in the PSR-0, "Foo \" end delimiter must be added to the namespace and escaped, to prevent "Foo" matched to such an accident "FooBar" occurs.
Class-map mode
{ "autoload": { "classmap": ["src/", "lib/", "Something.php"] } }
Perform composer install
updates automatically load, update execution Composer dump-the autoload . composer scans the specified directory to the file .php or .inc the end of the class, generate class to the specified file path mapping, and add the newly created vendor/composer/autoload_classmap.php
file. For example, a src / the BaseController
class, then the autoload_classmap.php
file, such a configuration will be generated:
'BaseController' => $baseDir . '/src/BaseController.php'
Examples of class manner There are two different situations.
- If you load the file has a namespace, press namespace instantiated.
- If no namespace, directly by the class name to instantiate.
Files mode
{ "autoload": { "files": ["src/MyLibrary/functions.php"] } }
Perform composer install
updates automatically load, update execution Composer dump-the autoload . Files way is to manually specify the file for immediate loading. For example, we have a series of global helper functions, can be placed in a helper file and then directly loaded, that is, when you use require 'vendor/autoload.php';
the automatic loader class loader will automatically load the files in the file came in, you used directly on the line.
Turn: https: //blog.csdn.net/ltx06/article/details/78820127