Composer
Package Manager
Composer
Overview
Composer is a dependency management tool for PHP that enables developers to declare, fetch, and manage libraries and packages required for projects. As the cornerstone of modern PHP development, it provides configuration management through composer.json files, automatic PSR-4 compliant autoloading, and integration with the Packagist repository. Seamlessly integrated with Laravel, Symfony, and other major PHP frameworks, Composer offers precise dependency resolution through version constraints and high-performance optimization options for production environments.
Details
Composer was developed in 2012 by Nils Adermann, Jordi Boggiano, and others, inspired by Node.js's npm and Ruby's Bundler. It has established itself as the standard dependency management tool for the PHP ecosystem and has significantly contributed to the adoption of PSR-0/PSR-4 autoloading conventions. Project metadata and dependencies are defined in the composer.json file, while exact versions are locked in the composer.lock file, ensuring consistency between development and production environments. Packagist serves as Composer's main repository, distributing PHP packages worldwide. Performance optimization features like classmap optimization, APCu cache, and authoritative classmaps enable fast class loading in production environments.
Pros and Cons
Pros
- Unified dependency management: Widely adopted as the standard tool in the PHP ecosystem
- Automatic autoloading: PSR-4/PSR-0 compliant automatic class loading
- Version constraints: Flexible dependency management through semantic versioning
- Framework integration: Complete integration with major frameworks like Laravel and Symfony
- Performance optimization: Multiple optimization options for production environments
- Rich ecosystem: Vast package library centered around Packagist
- Stability: Reproducible build environments through composer.lock
Cons
- Initial learning curve: Understanding dependency resolution concepts and commands required
- Disk space: Vendor directory can become large
- Dependency hell: Complex dependency conflicts can be difficult to resolve
- Network dependency: Internet connection required for package retrieval
- Security risks: Vulnerability risks from third-party packages
- Update complexity: Breaking changes during major version updates
Reference Links
- Composer Official Site
- Composer Documentation
- Packagist - PHP Package Repository
- Composer GitHub
- PSR-4 Autoloading Standard
- Composer Security Advisories
Code Examples
Basic Project Management
# Install Composer (global installation)
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
# Initialize project
composer init
# Install dependencies
composer install
# Add packages
composer require monolog/monolog
composer require phpunit/phpunit --dev
composer require laravel/framework
# Remove packages
composer remove monolog/monolog
# Update dependencies
composer update
composer update monolog/monolog
composer.json Configuration
{
"name": "mycompany/myproject",
"description": "A sample PHP project",
"type": "project",
"license": "MIT",
"authors": [
{
"name": "Developer Name",
"email": "[email protected]"
}
],
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": "^8.1",
"monolog/monolog": "^3.0",
"guzzlehttp/guzzle": "^7.0",
"symfony/console": "^6.0",
"doctrine/orm": "^2.10"
},
"require-dev": {
"phpunit/phpunit": "^10.0",
"friendsofphp/php-cs-fixer": "^3.0",
"phpstan/phpstan": "^1.0",
"mockery/mockery": "^1.5"
},
"autoload": {
"psr-4": {
"MyCompany\\MyProject\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"MyCompany\\MyProject\\Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit",
"cs-fix": "php-cs-fixer fix",
"analyze": "phpstan analyse",
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
]
},
"config": {
"optimize-autoloader": true,
"classmap-authoritative": true,
"apcu-autoloader": true,
"sort-packages": true
}
}
Autoloading Usage
<?php
// Load Composer autoloader
require_once __DIR__ . '/vendor/autoload.php';
// Use PSR-4 compliant classes
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use GuzzleHttp\Client;
use MyCompany\MyProject\SampleClass;
// Log configuration
$log = new Logger('app');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));
$log->warning('This is a warning message');
// HTTP client usage
$client = new Client();
$response = $client->request('GET', 'https://api.example.com/data');
// Custom class usage
$sample = new SampleClass();
$result = $sample->process();
// File autoload example
// src/helpers.php is automatically loaded
if (function_exists('custom_helper_function')) {
$output = custom_helper_function('input');
}
?>
Version Constraints and Updates
# Semantic versioning examples
composer require "monolog/monolog:^3.0" # 3.0.0 <= version < 4.0.0
composer require "guzzle/guzzle:~6.3.0" # 6.3.0 <= version < 6.4.0
composer require "symfony/console:>=5.0" # 5.0.0 or higher
# Development versions
composer require "vendor/package:dev-master"
composer require "vendor/package:dev-feature-branch"
# Specific stability levels
composer require "vendor/package:2.0.x-dev"
composer require "vendor/package:@dev"
# Version information
composer show
composer show monolog/monolog
composer show --installed
composer show --tree
# Update operations
composer update --dry-run # Preview changes
composer update --no-dev # Production (exclude dev dependencies)
composer update --with-dependencies # Update with dependencies
Project Creation and Framework Integration
# Laravel project creation
composer create-project laravel/laravel myapp
cd myapp
composer require laravel/breeze --dev
# Symfony project creation
composer create-project symfony/skeleton myapp
cd myapp
composer require webapp
# Slim and Laminas frameworks
composer create-project slim/slim-skeleton myapp
composer create-project laminas/laminas-mvc-skeleton myapp
# Framework-specific packages
composer require laravel/passport # Laravel OAuth2
composer require symfony/mailer # Symfony Mailer
composer require doctrine/migrations # Doctrine Migrations
# Development tools
composer require --dev barryvdh/laravel-debugbar
composer require --dev symfony/profiler-pack
Advanced Configuration and Performance Optimization
# Performance optimization (production)
composer install --no-dev --optimize-autoloader
composer dump-autoload --optimize --classmap-authoritative
# Enable APCu cache
composer install --apcu-autoloader
composer dump-autoload --apcu
# Platform requirements configuration
composer config platform.php 8.1.0
composer config platform.ext-mbstring 1.0.0
# Private repository configuration
composer config repositories.private-repo vcs https://github.com/company/private-repo
composer config repositories.company-satis composer https://packages.company.com
# Authentication configuration
composer config github-oauth.github.com YOUR_TOKEN
composer config http-basic.private-repo.com username password
# Cache management
composer clear-cache
composer config cache-files-ttl 86400
composer config cache-dir /tmp/composer-cache
Scripts and Workflow Automation
{
"scripts": {
"dev": [
"Composer\\Config::disableProcessTimeout",
"php -S localhost:8000 -t public"
],
"test": [
"phpunit --coverage-text",
"phpstan analyse src",
"php-cs-fixer fix --dry-run"
],
"deploy": [
"composer install --no-dev --optimize-autoloader",
"php artisan config:cache",
"php artisan route:cache",
"php artisan view:cache"
],
"post-update-cmd": [
"php artisan clear-compiled",
"php artisan optimize",
"@php artisan package:discover"
],
"pre-install-cmd": [
"echo 'Starting installation...'"
]
},
"scripts-descriptions": {
"dev": "Start development server",
"test": "Run all tests and code quality checks",
"deploy": "Deploy to production environment"
}
}
Security and Auditing
# Security audit (Laravel)
composer audit
# Advisory checks
composer require --dev roave/security-advisories:dev-latest
# Check package licenses
composer licenses
# Check outdated packages
composer outdated
composer outdated --direct
# Detect and fix vulnerable packages
composer update --with-dependencies
composer require package/name:^2.0 # Update to secure version
# Validate lock file
composer validate --strict
composer check-platform-reqs