agyanadda@gmail.com

PHP Namespaces and Composer

OOP and Advanced PHP 1 min read Updated Dec 1, 2026 Topic 35 of 36

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

Example — Namespaced classes with Composer autoloading PHP
<?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).

Test Yourself With Exercises

Exercise 1 Multiple Choice

What is Composer?

Exercise 2 True / False

You should commit the vendor folder to Git.

Exercise 3 Fill in the Blank

require 'vendor/___.php'; loads all Composer packages and your classes.

Frequently Asked Questions

Check that the namespace matches the folder path and the file name matches the class name, then run composer dump-autoload.