CodeBlanks Logo Icon CodeBlanks

Multi-level namespaces

PHP course · Advanced · Lesson 31/92

Learn the multi-level namespace structure in the Sub\Module\Class form.

Multi-level namespaces

You can split namespaces into sub-levels to build a hierarchy: App\Models\User, App\Services\Auth\Login. Here App is the vendor prefix, Models and Services are sub-levels.

Each \ is a level separator. PHP sees them as a tree: App is the root, Models and Services are branches. This structure keeps large projects organized.

Why is the vendor prefix important?

In the PSR-4 standard the vendor prefix is usually the producer or project name: Symfony\..., Laravel\..., Monolog\.... This prevents namespace clashes between different libraries.

In your own project, picking a unique prefix like App\... or MyCompany\Project\... is a good habit. The more unique the prefix, the lower the clash risk.

Exercise Define a multi-level namespace and class

Define namespace App\Services\Auth;. Add a Login class with public static function attempt($user) that prints the user name with a "Login: " prefix. Then call Login::attempt("Alex") and print __NAMESPACE__.

Show example solution
" . $user . "\n"; } }. Call Login::attempt("Alex"); and echo __NAMESPACE__ . "\n";.
Example solution:
<?php

namespace App\Services\Auth;

class Login {
    public static function attempt($user) {
        echo "Login: " . $user . "\n";
    }
}

Login::attempt("Alex");
echo __NAMESPACE__ . "\n";

Test yourself

  1. Complete the multi-level namespace declaration

    <?php
    ____ App\Models\Repository\UserRepository;
    
    $info = ["table" => "users"];
    class UserRepository {}
    
    Show answer
    <?php
    namespace App\Models\Repository\UserRepository;
    
    $info = ["table" => "users"];
    class UserRepository {}
    
  2. Match the multi-level namespace concepts

    App
    Vendor prefix
    \
    Level separator
    App\Models\User
    Three-level name
    App\Services\Auth
    Four-level name
  3. In App\Models\User, what is App?

    • A class name
    • The vendor prefix
    • A function name
    • A variable name
    Show answer

    The vendor prefix — Correct. App is the vendor prefix; it sets the project's root identity.

All lessons in Advanced