Composer and autoloading. Composer is PHP’s dependency manager. Even if you write zero third-party packages, use it for PSR-4 autoloading so you stop hand-writing require 'models/User.php' chains.
Install Composer
Download from getcomposer.org or install via your package manager. Run composer --version to confirm it works.
composer.json basics
In your project root, create composer.json:
{
"name": "example/my-app",
"require": {
"php": "^8.1"
},
"autoload": {
"psr-4": {
"App\": "src/"
}
}
}
The psr-4 block tells Composer: classes starting with App live under src/. Run composer install (or composer dump-autoload after changes) to generate vendor/autoload.php.
Using the autoloader
Require it once at the top of public/index.php:
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use AppControllersHomeController;
$controller = new HomeController();
$controller->index();
Adding a real dependency
Need an HTTP client or a template engine? Add it with Composer rather than downloading zip files:
composer require twig/twig
Composer updates composer.json and composer.lock. Commit both. The lock file pins exact versions so another machine gets the same packages.
composer.lock and vendor/
- Commit
composer.lockfor applications - Do not commit
vendor/– runcomposer installon deploy - Run
composer updatewhen you intentionally want newer versions
Class example
<?php
declare(strict_types=1);
namespace AppServices;
class Greeter
{
public function hello(string $name): string
{
return 'Hello, ' . Htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
}
}
File path: src/Services/Greeter.php. Namespace matches the folder structure. No manual require needed.
Composer is not Laravel-specific. WordPress plugins use it. Small scripts use it. If you outgrow a single file, reach for Composer before you invent your own autoloading.

