Posts Tagged ‘extending classes’

CakePHP: Extending the AppController

October 19th, 2009

Ever wanted to split off functionality to a base class other then AppController?

This is what was needed to prevent typing the same code over and over again in a project of mine.

The app controller is great and all, but it’s just one class and you might want some functionality in only a part of your controllers.

So lets get to work, what do we have?

  • AppController(app/app_controller.php)
  • ExtendedAppController(app/extended_app_controller.php)
  • MyController(app/my_controller.php)

Extending the app controller isn’t much work, all you need to know really is to put “App::import(‘Controller’, ‘ExtendedApp);” above the MyController.

Lets put it in code:

//app controller
class AppController extends Controller {
}
 
//extended app controller
class ExtendedAppController extends AppController {
 
}
 
//MyController
App::import('Controller', 'ExtendedApp);
class MyController extends PipeMsgHandlerController {
 
}

You don’t necessarily need to extend from AppController. If you have functionality in your app controller that you do not want to share with the ExtenedAppController then another option is to extend Controller.

Although I don’t recommend it, it’s better to split off the functionality you don’t want in the ExtendedController in another controller that inherits from the app controller for those controllers.