Composer for PHP Beginners: Dependencies and Autoloading
You're starting a new PHP project and need a library for logging or HTTP requests. You copy-paste some code, but it quickly becomes messy. How do you manage external libraries properly? Composer solves this by handling dependencies and autoloading for you. In this guide, you'll learn how to use Composer from scratch.
What is Composer?
Composer is a dependency manager for PHP. It allows you to declare the libraries your project depends on and manages them for you. It's not a package manager like apt or yum; it works per-project, installing dependencies into a vendor directory.
Installing Composer
First, check if Composer is already installed by running composer --version in your terminal. If not, download and install it from getcomposer.org. On Windows, use the Composer-Setup.exe installer. On macOS/Linux, run the installer script.
Creating a composer.json File
Every Composer project has a composer.json file that describes dependencies. You can create one manually or run:
composer init
This interactive command asks for package name, description, author, and dependencies. For now, you can skip adding dependencies and edit the file later.
Adding Dependencies
To add a library, use composer require. For example, to add the popular monolog/monolog logging library:
composer require monolog/monolog
Composer will download the library and its dependencies into the vendor directory and update composer.json and composer.lock.
Understanding Version Constraints
Composer uses semantic versioning. Common constraints:
^1.2allows updates to1.xbut not2.0(recommended for libraries).~1.2allows updates to1.2.xbut not1.3.1.2.*allows any1.2.xversion.>=1.2