Regarding Namespaces

I’m new to namespaces and just trying to get my head around it. I understand namespaces are mainly used to prevent conflicts in class names.

Previously in Yii 1.1 (which didn’t have namespaces) everything was “available”, for example if we want to use CHtml or CMenu we can just initialise these on the fly.

Now with Yii 2 we have to specifically "include" these classes in our files. For example the default layout file has:


use yii\helpers\Html;

use yii\bootstrap\Nav;

use yii\bootstrap\NavBar;

use yii\widgets\Breadcrumbs;

use app\assets\AppAsset;

And for every new class we want to use we need to include those classes too. Isn’t that more tedius / inconvenient? Was there really a big need for namespaces that I am just not understanding?

For me not having ToNameMyClassInSpecialWaysToAvoidConflictsWithOtherClasses makes up for all the other troubles that namespaces might bring(if any). You will get used to it after few days and will see that organization is just better when using namespaces.

Plus try using yii\db\Query and yii\elasticsearch\Query on the same page. Clash!

Namespaces make your code portable. That is, anyone can write a module that will operate in any Yii2 application without worrying about class-name conflicts.

You could write your own set of helper files that use various collections of classes and add them to your views using a single use statement.

QFE! It seems most of the time people are only using namespaces as a means for mapping library or application hierarchies. But their real purpose is to prevent said clashes.

Another point is that using namespaces is leveraging autoloading mechanisms as described in PSR-0/4, thus saving you from writing complex [font="Courier New"]include[/font] or [font="Courier New"]require[/font] statements.