← Tilbage til koncepter
Composer Autoloading
Automatisk loading af PHP classes med Composer's PSR-4 autoloader
Kategori: Tools
Foto: Nguyen Dang Hoang Nhu / Unsplash
Key Points
- +PSR-4 autoloading - Modern standard der mapper namespaces til directories
- +Classmap - Pre-computed map af alle klasser for hurtigere loading
- +Files autoloading - Inkluder specific files (helpers, functions) automatisk
- +Optimize autoloader - Generér classmap for production performance
- +composer dump-autoload - Regenerér autoloader efter ændringer
- +Namespace mapping - Definer root namespace til directory mapping i composer.json
- +Development vs production - Forskellige optimization strategies
- +Autoload-dev - Separate autoload config til development/testing
- +vendor/autoload.php - Single entry point der skal inkluderes
- +Class not found errors - Troubleshooting når autoloading fejler
Kode Eksempel
<?php
// composer.json configuration
// {
// "autoload": {
// "psr-4": {
// "App\\": "src/",
// "Database\\": "database/"
// },
// "files": [
// "src/helpers.php"
// ],
// "classmap": [
// "legacy/"
// ]
// },
// "autoload-dev": {
// "psr-4": {
// "Tests\\": "tests/"
// }
// }
// }
// File: src/Models/User.php
namespace App\Models;
class User {
public function __construct(
public string $name,
public string $email
) {}
public function getDisplayName(): string {
return ucfirst($this->name);
}
}
// File: src/Services/UserService.php
namespace App\Services;
use App\Models\User;
class UserService {
private array $users = [];
public function create(string $name, string $email): User {
$user = new User($name, $email);
$this->users[] = $user;
return $user;
}
public function getAll(): array {
return $this->users;
}
}
// File: src/helpers.php (loaded automatically via files autoload)
function app_url(string $path = ''): string {
return 'https://example.com/' . ltrim($path, '/');
}
function config(string $key, mixed $default = null): mixed {
// Load configuration value
return $default;
}
// File: public/index.php
require __DIR__ . '/../vendor/autoload.php';
use App\Models\User;
use App\Services\UserService;
// No need for require statements - classes are autoloaded
$userService = new UserService();
$user = $userService->create('John Doe', 'john@example.com');
echo $user->getDisplayName() . PHP_EOL;
echo app_url('dashboard') . PHP_EOL; // Helper from files autoload
// Running: composer dump-autoload
// Regenerates the autoloader with all mappingsHvornår bruges det?
- •Application bootstrapping - Inkluder vendor/autoload.php i entry point (index.php)
- •Package development - Definer PSR-4 mappings for dit package's namespace struktur
- •Legacy code integration - Brug classmap til at autoload ældre kode uden namespaces
- •Helper functions - Autoload utility functions via files directive
- •Testing setup - Brug autoload-dev til at autoload test classes og fixtures
- •Microservices - Hver service har sit eget autoload setup med separate namespaces
Best Practices
- +Følg PSR-4 standard strengt - ét namespace segment per directory niveau
- +Run 'composer dump-autoload -o' (optimize) i production for classmap generation
- +Placer vendor/autoload.php require som første statement i din application
- +Brug autoload-dev for test classes og development-only kode
- +Avoid mixing PSR-4 og classmap unless necessary for legacy support
- +Commit composer.lock til version control for reproducible builds
- +Run composer dump-autoload efter at tilføje nye classes eller ændre struktur
- +Organize kode i src/ directory og map det til dit root namespace i composer.json
Quick Info
Kategori
Tools
Sværhedsgrad
Begynder