Alisher Nasrullayev
Alisher Nasrullayev

Reputation: 645

How to add own namespace in Yii2

I have changed Yii2 advanced directory structure like following(it's working well):

app-folder
 -admin
   -assets
   -.htaccess
   -index.php
 -assets
 -protected
   -backend
     ...
   -common
     ...
   -frontend
     ...
   ...
 -uploads
 ...

Now, I am trying to add a namespace as namespace protected\base; into protected/base/AnyFile.php file and use it in a controller as use protected\base\AnyFile;. But, my project is giving error:

syntax error, unexpected 'protected' (T_PROTECTED), expecting identifier (T_STRING) or function (T_FUNCTION) or const (T_CONST) or \\ (T_NS_SEPARATOR)

I saw this issue on the website: Yii2 Custom / Shorter Namespace. However, It didn't work on my condition.

Upvotes: 1

Views: 1801

Answers (1)

Anton Rybalko
Anton Rybalko

Reputation: 1314

First of all protected is reserved keyword (token T_PROTECTED). You can keep direcory name but you need to change namespace root alias.

In your alias config file protected/common/bootstrap.php write:

Yii::setAlias('app', dirname(dirname(__DIR__))); // set path to protected directory

And then use namespace app\base; and use app\base\AnyFile;.

See Class Autoloading section of the guide https://www.yiiframework.com/doc/guide/2.0/en/concept-autoloading

Upvotes: 4

Related Questions