Chisskarzz
Chisskarzz

Reputation: 171

Yii 2 Custom Module Namespace for Models

Is there anyway to change the namespace of the Module and use it as a namespace of my models?

I'm building a project using the basic app template of yii2.

What I want is to have a centralized namespace so that when I use the module into different project and reuse the models inside it, (either basic or advanced template), I won't have to change the namespace based on its root directory.

Upvotes: 1

Views: 1294

Answers (2)

Irfan Ali
Irfan Ali

Reputation: 2258

This will possible with Yii2 aliases.

first put all your models in your custom folder and set it alias name Yii config file. like below

// an alias of a file path
Yii::setAlias('@myFolder', '/path/to/foo');

finally, update your all models namespace based on this alias one time. like below.

namespace myFolder\models\xxx;

now you can copy this folder to any yii2 app and just set alias name, like above i mention.

Note:- directory will be independent like below and namespace will based on this directory.

folderName
   ->models
       ->xxxxx
       ->xxxxx
        .....
// and namespace should add all the models like below
namespace folderName\models;

// while using these models, you can import like below
import myFolder\xxxxxx;

Upvotes: 1

ishengge
ishengge

Reputation: 39

You can edit the composer.json file find

{
   .....
 "autoload": {
        "psr-4": {
            "App\\": "src/" #<-key=namespace value=dirname
        }
  }
  ......
}

run composer update

Upvotes: 0

Related Questions