Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Namespace directory structure

Tags:

namespaces

php

It is my understanding that namespaces are declared as follows : vendor\module\classname.

And directory structure would be:

/Acme
    /Module1
        /src
            /Module1
                /Class.php

And a valid way to instantiate the class is : new Acme\Module1\Class();

Are my assumptions correct? If so, what's the benefit of using the src folder?

like image 727
ryy Avatar asked Nov 25 '13 17:11

ryy


1 Answers

Convention usually.

If you're using composer and you want to autoload your classes, it looks like you're trying to do PSR-0 autoloading.

So if you have "Acme": "src/"

Then in the same directory as your composer.json file would be a src folder, and in the src folder would be a Acme folder. All files in that folder would be namespace Acme; and all files in subdirectories of that folder would be namespace Acme\Subdirectory;.

In the console you need to type composer dump-autoload every time you make changes to the autoloading part of your composer.json file. (or for classmap autoloading, every time you add new files to directories being autoloaded.) This causes the files generated by composer to be updated. (you can find these files in the vendor/composer directory).

So if there was a src/Acme/Subdirectory/ClassName.php with a class in it named ClassName then to instantiate that class you could type new \Acme\Subdirectory\ClassName();

edit: so if this is your composer.json file

{
    "autoload": {
        "psr-0": {
            "Acme": "src/"
        }
    }
}

then your directory structure would be something like this

/ProjectRoot
    composer.json
    /src
        /Acme
            /Module1
                Class.php

And you would create a new instance of your class by typing

new \Acme\Module1\Class();
like image 58
echochamber Avatar answered Oct 14 '22 09:10

echochamber