use frontend models in backend

I have Yii2 Advance Template and having problem using frontend model in my backend code

The setup likes this

File frontend\models\Model1.php

namespace app\models;

class Model1 extend ActiveRecord

File backend\models\TestController

use app\models\Model1; //this is me error

use frontend\models\Model1; //this also give error

use frontend\app\models\Model1; // this also give error

so I google and find out that if I change the namespace in frontend\models\Model1.php

namespace frontend\models;

then in my backend code

use frontend\models\Model1; //this now works

The issue I have is i have 30+ frontend models and all of them are "namespace app\models". I can find/replace all "namespace app\models;" with "namespace frontend\models;" which is tedious and error prone.

Is there another way ?


What you have discovered is correct.

Like described here:

The alias @app and namespace "app" are always pointing to current application.


In backend "app" stands for the backend application.

In frontend "app" stands for the frontend application.

I would change all namespaces like you described.

Also I would think about putting the models into "common" since they are used by frontend and backend.

"Find and replace content in files of all selected folders" is possible with most editors.

Which Editor / IDE do you use?


I use NetBeans 7.4

it will be a pain but it possible as I will find

  • app\models\Model1; (e.g. use app\models\Model1;)

  • app\models\Model1: (e.g. app\models\Model1::find() )


Should I move every models to common\models directory and use "namespace common\models" ?

Or should I keep model files as is and change all frontend model from "namespace app\models" to "namespace frontend\models" ?


I usually handle it like this…


(Code used in frontend and backend)

frontend/models/User.php extends common/models/User.php

(extended code only used in frontend)

backend/models/User.php extends common/models/User.php

(extended code only used by backend)


thanks for sharing. :)