简体   繁体   中英

Yii 1.1: Can I have multiple base controllers?

There is a Controller class in protected/components that starts with the following comment:

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {
  ...

Can I define an alternative base controller, lets say Controller2 :

class Controller2 extends CController {
  ...

And derive some user controllers from it? Will it violate Yii architecture or introduce some flaws somehow?

Yes, you can have multiple base controllers. Default template represents pretty basic application so some concepts are simplified. In bigger applications having multiple base controllers is pretty common (for example separate modules can have its own base controller), although usually you have some hierarchy and there is one base controller at the top of inheritance tree.

You can have multiple base controllers which extends CController directly, but it may be harder to introduce app-specific behavior - in your case you would need to copy the same code to both Controller and Controller2 classes. So usually it is good practice to create app-level base controller which will be base for all controllers - even if it is empty at the beginning in may save you the trouble of changing each controller at a later stage of the project.

For example you may have separated base controllers for backend and frontend, which extends one app-level base controller:

class FrontendController extends Controller {
    // frontend-specific adjustments
}

class BackendController extends Controller {
    // backend-specific adjustments
}

class Controller extends CController {
    // app-specific adjustments (for backend and frontend)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM