Composer basics
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:
- Dependency Declaration: Define your project's external libraries (packages) in
composer.json(e.g.,ramsey/uuidfor UUIDs,guzzlehttp/guzzlefor HTTP requests). - Installation: Run
composer installin your project's root directory to download and install declared dependencies into thevendorfolder, respecting versions incomposer.lockif it exists, or creating it if not. - Adding New Packages: Use
composer require vendor/package-nameto add a new library, which updatescomposer.json,composer.lock, and installs the package. - Autoloading: Include
require 'vendor/autoload.php';at the top of your main PHP file to automatically load classes from installed packages, eliminating manualrequirestatements. - Updating/Managing: Use
composer updateto find newer versions of packages, andcomposer update vendor/packageto 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 fromcomposer.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.