Set up PHP Composer with global configuration, PSR-4 autoloading, and dependency management workflows for modern PHP development across Ubuntu, Debian, AlmaLinux, and Rocky Linux distributions.
Prerequisites
- Root or sudo access
- Basic PHP knowledge
- Command line familiarity
What this solves
PHP Composer is the standard dependency manager for PHP that handles package installation, autoloading, and version management. This tutorial configures Composer with global settings, implements PSR-4 autoloading for organized code structure, and establishes dependency management workflows for production-ready PHP applications.
Step-by-step installation
Install PHP and required extensions
Composer requires PHP with specific extensions for dependency resolution and package management functionality.
sudo apt update
sudo apt install -y php php-cli php-curl php-mbstring php-xml php-zip php-intl php-gd unzip curl
Download and install Composer
Download the official Composer installer and verify its integrity before installation.
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer
Verify Composer installation
Check that Composer is properly installed and accessible from the command line.
composer --version
composer diagnose
Configure global Composer settings
Set up global configuration for optimal performance and security.
composer config --global repo.packagist composer https://packagist.org
composer config --global process-timeout 2000
composer config --global cache-ttl 86400
Enable memory optimization
Configure Composer to handle large dependency trees efficiently.
composer config --global optimize-autoloader true
composer config --global classmap-authoritative true
composer config --global apcu-autoloader true
Set up PSR-4 autoloading
Create project structure
Set up a PHP project with proper PSR-4 directory structure for organized code management.
mkdir -p /var/www/myproject/{src,tests,public,config}
cd /var/www/myproject
Initialize Composer project
Create a composer.json file with project metadata and PSR-4 autoloading configuration.
composer init --name="example/myproject" --description="Example PHP project" --type="project" --license="MIT" --no-interaction
Configure PSR-4 autoloading
Edit composer.json to define namespace mapping for automatic class loading.
{
"name": "example/myproject",
"description": "Example PHP project",
"type": "project",
"license": "MIT",
"autoload": {
"psr-4": {
"App\\": "src/",
"App\\Controllers\\": "src/Controllers/",
"App\\Models\\": "src/Models/",
"App\\Services\\": "src/Services/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"require": {
"php": ">=8.1"
},
"require-dev": {
"phpunit/phpunit": "^10.0"
},
"config": {
"optimize-autoloader": true,
"classmap-authoritative": true,
"apcu-autoloader": true
}
}
Generate autoloader files
Create the autoloader files that enable automatic class loading based on PSR-4 mapping.
composer dump-autoload --optimize
Create example classes
Create sample classes to demonstrate PSR-4 autoloading functionality.
Create model example
Add a model class to demonstrate namespace organization.
name = $name;
$this->email = $email;
}
public function getName(): string
{
return $this->name;
}
public function getEmail(): string
{
return $this->email;
}
}
Create bootstrap file
Set up an entry point that loads the Composer autoloader and demonstrates class usage.
index() . "\n";
echo "User: " . $user->getName() . " (" . $user->getEmail() . ")\n";
Implement dependency management
Install production dependencies
Add commonly used packages for modern PHP development.
composer require monolog/monolog vlucas/phpdotenv symfony/http-foundation
Install development dependencies
Add tools for testing, debugging, and code quality analysis.
composer require --dev phpunit/phpunit phpstan/phpstan squizlabs/php_codesniffer
Configure scripts for development workflow
Add custom scripts to composer.json for common development tasks.
{
"scripts": {
"test": "phpunit",
"test-coverage": "phpunit --coverage-html coverage",
"analyse": "phpstan analyse src --level=7",
"cs-check": "phpcs src --standard=PSR12",
"cs-fix": "phpcbf src --standard=PSR12",
"dev-setup": [
"composer install",
"composer dump-autoload --optimize"
],
"prod-deploy": [
"composer install --no-dev --optimize-autoloader",
"composer dump-autoload --classmap-authoritative --no-dev"
]
}
}
Set up environment-specific configurations
Configure different dependency sets for development and production environments.
composer config platform.php 8.1
composer config preferred-install dist
composer config sort-packages true
Create production optimization script
Set up a deployment script for production environment optimization.
#!/bin/bash
Production deployment script
echo "Starting production deployment..."
Update dependencies
composer install --no-dev --optimize-autoloader --no-interaction
Generate optimized autoloader
composer dump-autoload --classmap-authoritative --no-dev
Clear any development caches
php -r "opcache_reset();"
echo "Production deployment completed."
chmod +x deploy.sh
Configure security and performance settings
Set up secure package repositories
Configure Composer to use HTTPS and verify package signatures.
composer config --global secure-http true
composer config --global disable-tls false
composer config --global cafile /etc/ssl/certs/ca-certificates.crt
Configure cache and performance settings
Optimize Composer for better performance with caching and parallel downloads.
composer config --global cache-dir ~/.composer/cache
composer config --global cache-files-ttl 86400
composer config --global cache-repo-ttl 86400
composer config --global htaccess-protect false
Set proper file permissions
Configure secure file permissions for the project directory and Composer cache.
sudo chown -R www-data:www-data /var/www/myproject
sudo find /var/www/myproject -type d -exec chmod 755 {} \;
sudo find /var/www/myproject -type f -exec chmod 644 {} \;
sudo chmod +x /var/www/myproject/deploy.sh
Verify your setup
composer --version
composer validate
composer show --installed
composer diagnose
php public/index.php
Check that autoloading works correctly:
cd /var/www/myproject
composer dump-autoload --optimize
php -r "require 'vendor/autoload.php'; echo 'Autoloader works!\n';"
Common issues
| Symptom | Cause | Fix |
|---|---|---|
| Class not found errors | Incorrect PSR-4 mapping or missing autoload dump | composer dump-autoload --optimize |
| Memory limit exceeded | Large dependency resolution | php -d memory_limit=2G composer install |
| SSL certificate errors | Outdated CA certificates | Update system certificates and set composer config --global secure-http true |
| Permission denied on vendor/ | Incorrect directory ownership | sudo chown -R $USER:$USER vendor/ |
| Composer commands hang | Network timeout issues | composer config --global process-timeout 3000 |
| Autoloader not optimized | Missing optimization flags | composer install --optimize-autoloader --classmap-authoritative |
Next steps
- Set up NGINX with modern security headers for web server configuration
- Configure PHP 8.4 with Apache for production hosting
- Optimize PHP-FPM performance for high-traffic applications
- Configure PHP code quality tools with PHPStan and PHP_CodeSniffer
- Set up PHP application monitoring and logging for production environments
Running this in production?
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Default values
PROJECT_NAME="${1:-myproject}"
PROJECT_PATH="/var/www/${PROJECT_NAME}"
PROJECT_NAMESPACE="${2:-App}"
# Usage message
usage() {
echo "Usage: $0 [project_name] [namespace]"
echo " project_name: Name of the PHP project (default: myproject)"
echo " namespace: Base namespace for PSR-4 autoloading (default: App)"
echo "Example: $0 webapp MyApp"
exit 1
}
# Cleanup function
cleanup() {
echo -e "${RED}[ERROR] Installation failed. Cleaning up...${NC}"
if [[ -d "$PROJECT_PATH" ]]; then
rm -rf "$PROJECT_PATH"
fi
}
# Set up error handling
trap cleanup ERR
# Check if running as root or with sudo
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}[ERROR] This script must be run as root or with sudo${NC}"
exit 1
fi
# Auto-detect distro
echo -e "${YELLOW}[1/8] Detecting operating system...${NC}"
if [[ -f /etc/os-release ]]; then
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_UPDATE="apt update"
PKG_INSTALL="apt install -y"
;;
almalinux|rocky|centos|rhel|ol)
PKG_MGR="dnf"
PKG_UPDATE="dnf update -y"
PKG_INSTALL="dnf install -y"
;;
fedora)
PKG_MGR="dnf"
PKG_UPDATE="dnf update -y"
PKG_INSTALL="dnf install -y"
;;
amzn)
PKG_MGR="yum"
PKG_UPDATE="yum update -y"
PKG_INSTALL="yum install -y"
;;
*)
echo -e "${RED}[ERROR] Unsupported distribution: $ID${NC}"
exit 1
;;
esac
echo -e "${GREEN}Detected: $PRETTY_NAME${NC}"
else
echo -e "${RED}[ERROR] Cannot detect operating system${NC}"
exit 1
fi
# Update package manager
echo -e "${YELLOW}[2/8] Updating package manager...${NC}"
$PKG_UPDATE
# Install PHP and required extensions
echo -e "${YELLOW}[3/8] Installing PHP and required extensions...${NC}"
if [[ "$PKG_MGR" == "apt" ]]; then
$PKG_INSTALL php php-cli php-curl php-mbstring php-xml php-zip php-intl php-gd unzip curl
elif [[ "$PKG_MGR" == "dnf" || "$PKG_MGR" == "yum" ]]; then
$PKG_INSTALL php php-cli php-curl php-mbstring php-xml php-zip php-intl php-gd unzip curl
fi
# Verify PHP installation
if ! command -v php &> /dev/null; then
echo -e "${RED}[ERROR] PHP installation failed${NC}"
exit 1
fi
PHP_VERSION=$(php -r "echo PHP_VERSION;")
echo -e "${GREEN}PHP $PHP_VERSION installed successfully${NC}"
# Download and install Composer
echo -e "${YELLOW}[4/8] Downloading and installing Composer...${NC}"
cd /tmp
curl -sS https://getcomposer.org/installer | php
# Verify Composer installer
if [[ ! -f composer.phar ]]; then
echo -e "${RED}[ERROR] Composer download failed${NC}"
exit 1
fi
# Install Composer globally
mv composer.phar /usr/local/bin/composer
chmod 755 /usr/local/bin/composer
# Verify Composer installation
echo -e "${YELLOW}[5/8] Verifying Composer installation...${NC}"
if ! command -v composer &> /dev/null; then
echo -e "${RED}[ERROR] Composer installation failed${NC}"
exit 1
fi
COMPOSER_VERSION=$(composer --version --no-ansi | head -n1)
echo -e "${GREEN}$COMPOSER_VERSION installed successfully${NC}"
# Configure global Composer settings
echo -e "${YELLOW}[6/8] Configuring global Composer settings...${NC}"
composer config --global repo.packagist composer https://packagist.org
composer config --global process-timeout 2000
composer config --global cache-ttl 86400
composer config --global optimize-autoloader true
composer config --global classmap-authoritative true
composer config --global apcu-autoloader true
echo -e "${GREEN}Global Composer configuration completed${NC}"
# Create project structure
echo -e "${YELLOW}[7/8] Setting up PHP project with PSR-4 structure...${NC}"
mkdir -p "$PROJECT_PATH"/{src,tests,public,config}
mkdir -p "$PROJECT_PATH/src"/{Controllers,Models,Services}
cd "$PROJECT_PATH"
# Create composer.json with PSR-4 autoloading
cat > composer.json << EOF
{
"name": "example/${PROJECT_NAME}",
"description": "Example PHP project with Composer dependency management",
"type": "project",
"license": "MIT",
"autoload": {
"psr-4": {
"${PROJECT_NAMESPACE}\\\\": "src/",
"${PROJECT_NAMESPACE}\\\\Controllers\\\\": "src/Controllers/",
"${PROJECT_NAMESPACE}\\\\Models\\\\": "src/Models/",
"${PROJECT_NAMESPACE}\\\\Services\\\\": "src/Services/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\\\": "tests/"
}
},
"require": {
"php": ">=8.1"
},
"require-dev": {
"phpunit/phpunit": "^10.0"
},
"config": {
"optimize-autoloader": true,
"classmap-authoritative": true,
"apcu-autoloader": true
}
}
EOF
# Install dependencies and generate autoloader
composer install --optimize-autoloader --no-dev
# Create example classes to demonstrate PSR-4 autoloading
cat > "src/Application.php" << EOF
<?php
namespace ${PROJECT_NAMESPACE};
class Application
{
public function run(): string
{
return "Hello from ${PROJECT_NAMESPACE} Application!";
}
}
EOF
cat > "src/Controllers/HomeController.php" << EOF
<?php
namespace ${PROJECT_NAMESPACE}\\Controllers;
class HomeController
{
public function index(): string
{
return "Welcome to the Home Controller!";
}
}
EOF
cat > "public/index.php" << EOF
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use ${PROJECT_NAMESPACE}\\Application;
use ${PROJECT_NAMESPACE}\\Controllers\\HomeController;
\$app = new Application();
\$controller = new HomeController();
echo \$app->run() . PHP_EOL;
echo \$controller->index() . PHP_EOL;
EOF
# Set proper permissions
chown -R www-data:www-data "$PROJECT_PATH" 2>/dev/null || chown -R apache:apache "$PROJECT_PATH" 2>/dev/null || true
find "$PROJECT_PATH" -type d -exec chmod 755 {} \;
find "$PROJECT_PATH" -type f -exec chmod 644 {} \;
echo -e "${GREEN}Project structure created at $PROJECT_PATH${NC}"
# Final verification
echo -e "${YELLOW}[8/8] Running final verification...${NC}"
# Test Composer
composer diagnose --no-interaction &>/dev/null || echo -e "${YELLOW}Warning: Composer diagnose found some issues${NC}"
# Test PSR-4 autoloading
cd "$PROJECT_PATH"
if php public/index.php &>/dev/null; then
echo -e "${GREEN}PSR-4 autoloading verification: PASSED${NC}"
else
echo -e "${YELLOW}Warning: PSR-4 autoloading test failed${NC}"
fi
echo -e "${GREEN}===========================================${NC}"
echo -e "${GREEN}PHP Composer installation completed!${NC}"
echo -e "${GREEN}===========================================${NC}"
echo -e "Project path: ${GREEN}$PROJECT_PATH${NC}"
echo -e "Test the installation: ${GREEN}cd $PROJECT_PATH && php public/index.php${NC}"
echo -e "Add dependencies: ${GREEN}composer require package/name${NC}"
echo -e "Update autoloader: ${GREEN}composer dump-autoload --optimize${NC}"
Review the script before running. Execute with: bash install.sh