DEV Community

Cover image for PHP Namespaces are not the same as the Directory Structure
Gaurav Makhecha
Gaurav Makhecha

Posted on • Originally published at blog.freshbits.in

PHP Namespaces are not the same as the Directory Structure

Let's start with a question: We have a PHP class SalesController.php with the namespace App/Http/Controllers and it is located at app/Http/Controllers/SalesController.php

Where do you think the class Sale.php with the namespace App/Domain/Sales would be located?

Did you say app/Domain/Sales/Sale.php? Are you sure?

...

Well, it is located at src/Domain/Sales/Sale.php and it works.

Why so

Thanks to the PSR-4 autoloading, we can define the namespaces prefix and their corresponding base directories.

Following is the composer configuration to clear the doubt:

{
    "autoload": {
        "psr-4": {
            "App\\Http\\": "app/Http",
            "App\\Domain\\": "src/Domain"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Reasoning

First of all, namespacing allows you to divide your code files into multiple groups. That allows you to set the same name for two different classes as far as they belong to different namespaces.

This flexibility allows developers to follow their own conventions over the framework conventions keeping all the parties happy.

One additional benefit when using namespaces in the code is easier directory renames. No need to do 'find & replace' in all the files that require your classes. Changing the base directory of the namespace does the job.

Fun Fact

You can set multiple base directories for a single namespace prefix. Example:

{
    "autoload": {
        "psr-4": { "Domain\\": ["src/", "lib/"] }
    }
}
Enter fullscreen mode Exit fullscreen mode

Not sure why one would go for this as it is a bit confusing. But it's possible, however.

Story ends

In case you cannot find a class or directory by following the namespace words, do check the autoload config once. You may get the answer. Sayonara!


Credits - Cover Photo by Randy Fath on Unsplash

Top comments (0)