Lab 11: Composer Advanced

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm composer:2 sh

Composer is PHP's dependency manager. Beyond basic require, it supports custom scripts, path repositories, autoload optimization, platform requirements, security audits, and plugins.


Step 1: Initializing a Project

docker run --rm composer:2 sh -c "
mkdir /tmp/myapp && cd /tmp/myapp &&
composer init \
  --no-interaction \
  --name=myorg/myapp \
  --description='Advanced Composer demo' \
  --type=project \
  --php='>=8.1' 2>&1 | tail -5 &&
echo '---' &&
cat composer.json
"

📸 Verified Output:

Writing ./composer.json
---
{
    "name": "myorg/myapp",
    "description": "Advanced Composer demo",
    "type": "project",
    "require": {
        "php": ">=8.1"
    }
}

Step 2: Custom Scripts

Add lifecycle scripts to composer.json:

💡 @php runs the PHP interpreter found by Composer. @scriptname calls another defined script. Scripts can be arrays (run in sequence).


Step 3: Autoloading Strategies

📸 Verified Output:


Step 4: Platform Requirements

💡 Platform requirements prevent deploying code to servers missing required extensions. Always specify ext-* for extensions your code requires.


Step 5: Path Repositories (Monorepo / Local Packages)

📸 Verified Output:


Step 6: Security Audit

📸 Verified Output:

💡 Run composer audit in CI pipelines to catch known vulnerabilities before deployment.


Step 7: Composer Plugins & Configuration

💡 allow-plugins (Composer 2.2+) explicitly whitelists plugins that can run code during install. Security best practice.


Step 8: Capstone — Full Project Setup

📸 Verified Output:


Summary

Feature
Command/Config
Notes

Initialize project

composer init

Interactive or --no-interaction

Path repository

{"type": "path", "url": "../pkg"}

Local monorepo packages

PSR-4 autoload

"autoload": {"psr-4": {...}}

Standard namespace mapping

Classmap autoload

"classmap": ["src/Legacy/"]

Non-standard file structure

Optimize autoloader

composer dump-autoload -o

Production: classmap-authoritative

Platform requirements

"ext-pdo": "*" in require

Prevent missing extension deploys

Custom scripts

"scripts": {"test": "phpunit"}

Lifecycle hooks + custom commands

Security audit

composer audit

Check known CVEs

Allow plugins

"allow-plugins": {...}

Required since Composer 2.2

Check outdated

composer outdated

Find available updates

Last updated