Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp: Abstracting AppController another level, possible?

I was wondering if it's somehow possible to add another abstraction controller between AppController and my app's other controllers?

So that my controllers, e.g. UsersController extends SecureController and SecureController extends AppController.

Also I want to be able to have other controllers extend AppController directly: SomeNonSecureController extends AppController.

this is because my current AppController has all sorts of Auth and ACL stuff in its beforeFilter, but i also have controllers that don't need that security stuff (before everything needed the security, no new specs have been added).. but because some many controllers do need it, it doesn't make sense to copy-paste the code to all needy controllers.

I was thinking to but all the beforeFilter security stuff into a SecureController - that way any controllers that need security simpley extend it, while others inherit from AppController directly.

How would you go on about doing something like this?

Thanks in advance, Ken.

like image 776
Ken Avatar asked Dec 09 '09 18:12

Ken


2 Answers

My first thoughts would be to see if I could abstract some of the functionality from the beforeFilter into a component - remember components can use other components too, just include them in your component's $components property, so you can access the AuthComponent and AclComponent etc.

If this was not suitable then I'd go for your route, in order to do it, just include('secure_controller.php'); before your individual controller class declaration in it's file.

I have done something similar by creating a BaseController that I use in all my projects which provides all my admin CRUD actions that are standard. I then have my AppController extend this which contains application specific, controller wide functionality, then individual controllers extend that, and end up being practically empty. All I do is:

// app/base_controller.php
<?php class BaseController extends Controller {} ?>

// app/app_controller.php
<?php
include('base_controller.php');
class AppController extends BaseController {}
?>

// app/controllers/my_controller.php
<?php class MyController extends AppController {} ?>
like image 193
neilcrookes Avatar answered Nov 03 '22 20:11

neilcrookes


I've just been attempting this too. It seems it's relatively simple to extend any controller with any other one. In Cake 2.0 you just use the import() statement (include() does a similar thing).

App::import('Controller', 'Security');
class SecureAreaController extends SecurityController {
    // extra functionality *not* in base class goes here
}
like image 1
Simon East Avatar answered Nov 03 '22 18:11

Simon East