Cakephp: Abstracting AppController another level, possible?

末鹿安然 提交于 2019-12-07 02:39:45

问题


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.


回答1:


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 {} ?>



回答2:


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
}


来源:https://stackoverflow.com/questions/1875831/cakephp-abstracting-appcontroller-another-level-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!