Namespaces
Namespaces stop name clashes — two User classes can live in different namespaces:
namespace App\Models;
class User { }
Use it from another file:
use App\Models\User;
$user = new User();
The namespace usually matches the folder: App\Models\User → app/Models/User.php.
Composer
Composer is PHP's package manager (like npm for JavaScript).
composer init
composer require phpmailer/phpmailer
composer require nesbot/carbon
Packages go into the vendor/ folder, listed in composer.json.
Autoloading (PSR-4)
Tell Composer where your classes live:
"autoload": { "psr-4": { "App\\": "app/" } }
Run composer dump-autoload, then load everything with one line:
require __DIR__ . '/vendor/autoload.php';
No more long lists of require statements. This is exactly how Laravel loads its classes.
Do not commit vendor/ to Git — run composer install instead.
Example
<?php
// ---- app/Services/FeeCalculator.php ----
namespace App\Services;
class FeeCalculator
{
public function __construct(private float $gstRate = 18) {}
public function total(float $fee): float
{
return round($fee * (1 + $this->gstRate / 100), 2);
}
}
// ---- app/Models/Course.php ----
// namespace App\Models;
// class Course { public function __construct(public string $title, public float $fee) {} }
// ---- index.php ----
// require __DIR__ . '/vendor/autoload.php';
//
// use App\Models\Course;
// use App\Services\FeeCalculator;
// use Carbon\Carbon; // installed with: composer require nesbot/carbon
//
// $course = new Course('PHP Masterclass', 4999);
// $calc = new FeeCalculator();
// echo $course->title . ': ₹' . $calc->total($course->fee) . '<br>';
// echo 'Batch starts ' . Carbon::now()->addWeek()->format('d M Y');
With composer.json autoload set to "App\\": "app/" and composer dump-autoload run, index.php prints: PHP Masterclass: ₹5898.82 / Batch starts (next week's date).