Composer & Autoloading
Autoloading
The function spl_autoload_register() allows to register a function that will be invoked when PHP needs to load a class/interface defined by the user.
In autoload.php:
In file.php:
Note: will fuck up if namespaces exists.
Multiple Autoloading
It's possible to resister multiple autoloading functions by calling spl_autoload_register() multiple times.
| PHP | |
|---|---|
Composer
Open Source project for dependency management and autoloading of PHP libraries and classes.
Composer uses composer.json to define dependencies with third-party libraries.
Libraries are downloaded through Packagist and GitHub.
In composer.json:
Installing Dependencies
In the same folder of composer.json execute composer install.
Composer will create:
vendor: folder containing all requested librariesvendor\autoload.php: file for class autoloadingcomposer.lock
In alternative composer require <lib> will add the library to the project and create a composer.json if missing.
Note: to ignore the php version use
composer <command> --ignore-platform-reqs
Updating Dependencies
To update dependencies use composer update. To update only the autoloading section use composer dump-autoload.
Autoloading Project Classes
Composer can also autoload classes belonging to the current project. It's sufficient to add the autoload keyword in the JSON and specify the path and autoload mode.