Skip to main content

Composer basics


To start using Composer in your project, all you need is a composer.json file. This file describes the dependencies of your project and may contain other ...See more


Composer basics revolve around it being dependency manager for PHP, letting you declare libraries your project needs in a composer.json file, and then automatically installing, updating, and autoloading them via simple command-line tools like composer install and composer require, saving immense time by managing third-party code (like Guzzle, PHPUnit) so you don't have to manually find and manage them. It works per-project, creating a vendor directory and an autoload.php file for seamless class loading, similar to npm for JavaScript or Bundler for Ruby. 
This video provides a beginner-friendly introduction to Composer:

Core Concepts & Workflow:
  1. Dependency Declaration: Define your project's external libraries (packages) in composer.json (e.g., ramsey/uuid for UUIDs, guzzlehttp/guzzle for HTTP requests).
  2. Installation: Run composer install in your project's root directory to download and install declared dependencies into the vendor folder, respecting versions in composer.lock if it exists, or creating it if not.
  3. Adding New Packages: Use composer require vendor/package-name to add a new library, which updates composer.jsoncomposer.lock, and installs the package.
  4. Autoloading: Include require 'vendor/autoload.php'; at the top of your main PHP file to automatically load classes from installed packages, eliminating manual require statements.
  5. Updating/Managing: Use composer update to find newer versions of packages, and composer update vendor/package to update specific ones. 
You can watch this video to see how to use Composer to install packages:

Key Files & Folders:
  • composer.json: Your project's manifest, listing dependencies and versions.
  • composer.lock: Locks exact package versions to ensure consistent installations across environments.
  • vendor/: Directory where Composer installs all downloaded packages and the autoloader. 
This video explains the initial setup and use of Composer:

Basic Commands:
  • composer install: Installs dependencies from composer.json / composer.lock.
  • composer require vendor/package: Adds and installs a new package.
  • composer update: Updates packages to newer compatible versions.
  • composer dump-autoload: Regenerates the autoloader.