Reputation: 1599
I seem to come across a couple of flavours of laravel namespace definitions (in the classes) and I'm wondering if some are better than others, or maybe even plain wrong.
namespace mydomain\app\controllers
namespace dev.mydomain.com\app\controllers
namespace app\controllers
namespace \app\controllers
A couple of questions:
\
is optional, but what the mydomain prefix? Is it required, or optional? dev.mydomain.com
is or just mydomain
?Upvotes: 2
Views: 82
Reputation: 2307
There is nothing better or worse in those namespaces you mention.
Namespaces were added to language to prevent name clashes in separate packages.
For example, you can have a class User
in your own namespace \MyApp\User
, and also use a third party package that has a class named User
, but in its own namespace \Package\User
.
That was the initial idea. Later, people decided that we can use this namespaces to auto-load some classes. A raw idea is that \MyApp\User
should be found in MyApp/User.php
. Pretty simple.
This has advanced of course, that you can read more about by searching "php autoloading" or better "composer autoloading".
And about that initial \
, it does not matter in some places, but it matters somewhere else. When declaring a namespace it does not matter, e.g. namespace \MyApp\User
is the same as namespace MyApp\User
. Also the use
statement behaves like this. But when you are going to use a class, i.e. new \MyApp\User()
vs new MyApp\User
, it does differ. You can find more information in PHP documentation.
Ok, enough background. Your questions specifically.
I know the initial \ is optional, but what the mydomain prefix? Is it required, or optional?
As for Laravel case, it is not optional. Look at composer.json
, under psr-4
you will find that the app
folder has a defined prefix for namespace. That is what you should use for your classes (If they are in app
folder). To read more, look for PSR-4.
does it make a difference to use dev.mydomain.com is or just mydomain ?
I think I already mentioned the PSR-4, so use whatever is there.
Is it simply a matter of being the same as the folder names?
That is also the PSR-4. Read more about it, and all your questions are answered.
But in short, we have two standards for autoloading classes based on namespaces in PHP: PSR-0 and PSR-4.
In PSR-0 (the old one), The directory structure had to match the namespace exactly, that is if your root folder were src
and you class was named \Package\User
, then you had src/Package/User.php
in your file system.
In PSR-4, we can have namespace prefix for a directory. For example, you say that whatever is in folder src
, it just starts with \App\Package
namespace. The a class named \App\Package\User
should reside in src/User.php
, with correct namespace of course. That is what being used by Laravel, and most packages these days.
Upvotes: 1