PHP Composer and Autoloading
Use when composer package management and PSR-4 autoloading including dependency management, autoload strategies, package creation, version constraints, and patterns for modern PHP project organization and distribution.
What this skill does
# PHP Composer and Autoloading
## Introduction
Composer is PHP's de facto dependency manager, handling package installation,
autoloading, and version management. PSR-4 autoloading eliminates manual
require statements by automatically loading classes based on namespace and file
structure conventions.
Composer revolutionized PHP development by providing standardized dependency
management similar to npm, pip, or Maven. Combined with PSR-4 autoloading,
Composer enables modern PHP projects to organize code cleanly, share packages
easily, and manage dependencies reliably.
This skill covers Composer basics, dependency management, autoloading strategies,
package creation, semantic versioning, and best practices for maintainable PHP
projects.
## Composer Basics
Composer manages project dependencies through composer.json configuration and
installs packages into the vendor directory.
```json
{
"name": "company/project",
"description": "Project description",
"type": "project",
"require": {
"php": ">=8.1",
"symfony/console": "^6.0",
"guzzlehttp/guzzle": "^7.5",
"monolog/monolog": "^3.0"
},
"require-dev": {
"phpunit/phpunit": "^10.0",
"phpstan/phpstan": "^1.10",
"squizlabs/php_codesniffer": "^3.7"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit",
"lint": "phpcs",
"analyse": "phpstan analyse"
},
"config": {
"optimize-autoloader": true,
"sort-packages": true
}
}
```
```bash
# Install dependencies
composer install
# Install specific package
composer require symfony/http-foundation
# Install development dependency
composer require --dev symfony/var-dumper
# Update dependencies
composer update
# Update specific package
composer update monolog/monolog
# Remove package
composer remove guzzlehttp/guzzle
# Show installed packages
composer show
# Show outdated packages
composer outdated
# Validate composer.json
composer validate
# Run script
composer test
```
Composer creates composer.lock to lock exact dependency versions, ensuring
consistent installations across environments.
## PSR-4 Autoloading
PSR-4 autoloading maps namespaces to directories, automatically loading classes
without manual require statements.
```php
<?php
// composer.json autoload configuration
{
"autoload": {
"psr-4": {
"App\\": "src/",
"App\\Controllers\\": "src/Controllers/",
"App\\Models\\": "src/Models/"
}
}
}
// Directory structure
// src/
// User.php
// Controllers/
// UserController.php
// Models/
// UserModel.php
// src/User.php
namespace App;
class User {
public function __construct(
public string $name,
public string $email
) {}
}
// src/Controllers/UserController.php
namespace App\Controllers;
use App\User;
use App\Models\UserModel;
class UserController {
public function show(int $id): User {
$model = new UserModel();
return $model->find($id);
}
}
// src/Models/UserModel.php
namespace App\Models;
use App\User;
class UserModel {
public function find(int $id): User {
return new User("Alice", "[email protected]");
}
}
// index.php - Composer autoloader
require __DIR__ . '/vendor/autoload.php';
use App\Controllers\UserController;
$controller = new UserController();
$user = $controller->show(1);
echo $user->name; // "Alice"
```
```php
<?php
// Multiple autoload strategies
{
"autoload": {
"psr-4": {
"App\\": "src/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"src/helpers.php"
]
}
}
// Regenerate autoloader after changes
// composer dump-autoload
// Optimize autoloader for production
// composer dump-autoload --optimize
// composer dump-autoload --classmap-authoritative
```
PSR-4 eliminates require statements and enables consistent project structure
across PHP projects.
## Version Constraints and Dependency Management
Semantic versioning and version constraints control which package versions
Composer installs and updates.
```json
{
"require": {
"vendor/package": "1.2.3",
"vendor/exact": "1.0.0",
"vendor/caret": "^2.0",
"vendor/tilde": "~3.1",
"vendor/wildcard": "4.*",
"vendor/range": ">=5.0 <6.0",
"vendor/latest": "dev-master",
"vendor/branch": "dev-feature-x",
"vendor/stability": "1.0@beta"
}
}
```
Version constraint patterns:
- `1.2.3` - Exact version
- `^1.2.3` - Caret: >=1.2.3 <2.0.0 (compatible)
- `~1.2.3` - Tilde: >=1.2.3 <1.3.0 (similar)
- `1.*` - Wildcard: >=1.0.0 <2.0.0
- `>=1.0 <2.0` - Range: explicit min/max
- `dev-master` - Development branch
- `1.0@beta` - Specific stability
```json
{
"require": {
"symfony/console": "^6.0",
"monolog/monolog": "^3.0",
"guzzlehttp/guzzle": "^7.5"
},
"minimum-stability": "stable",
"prefer-stable": true
}
```
```bash
# Show why package installed
composer why vendor/package
# Show what depends on package
composer depends vendor/package
# Show what package provides
composer show --all vendor/package
# Check for security vulnerabilities
composer audit
# Show platform requirements
composer check-platform-reqs
# Diagnose issues
composer diagnose
```
Semantic versioning (MAJOR.MINOR.PATCH) communicates breaking changes,
features, and fixes in version numbers.
## Creating Packages
Creating reusable Composer packages enables code sharing across projects and
with the community.
```json
{
"name": "company/http-client",
"description": "HTTP client wrapper",
"type": "library",
"keywords": ["http", "client", "api"],
"license": "MIT",
"authors": [
{
"name": "Developer Name",
"email": "[email protected]"
}
],
"require": {
"php": ">=8.1",
"guzzlehttp/guzzle": "^7.5"
},
"require-dev": {
"phpunit/phpunit": "^10.0"
},
"autoload": {
"psr-4": {
"Company\\HttpClient\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
}
}
```
```php
<?php
// src/Client.php
namespace Company\HttpClient;
use GuzzleHttp\Client as GuzzleClient;
class Client {
private GuzzleClient $client;
public function __construct(string $baseUrl) {
$this->client = new GuzzleClient(['base_uri' => $baseUrl]);
}
public function get(string $path): array {
$response = $this->client->get($path);
return json_decode($response->getBody(), true);
}
public function post(string $path, array $data): array {
$response = $this->client->post($path, ['json' => $data]);
return json_decode($response->getBody(), true);
}
}
// tests/ClientTest.php
namespace Tests;
use Company\HttpClient\Client;
use PHPUnit\Framework\TestCase;
class ClientTest extends TestCase {
public function testCanCreateClient(): void {
$client = new Client('https://api.example.com');
$this->assertInstanceOf(Client::class, $client);
}
}
```
```bash
# Validate package
composer validate
# Initialize new package
composer init
# Publish to Packagist
# 1. Create GitHub repository
# 2. Push code with composer.json
# 3. Submit to packagist.org
# Private packages
# Add to composer.json:
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/company/private-package"
}
]
}
```
Well-designed packages follow PSR standards, include tests, and provide clear
documentation.
## Autoload Optimization
Optimizing autoloading improves production performance by reducing file system
lookups.
```bash
# GeneratRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.