我不认为这是一个有争议的问题。将管理功能放在它们各自的控制器中(即,不是全部放在一个“管理”控制器中),并使用 Cake 内置的“管理”前缀路由来保证它们的安全。这是 CakePHP 认可的方式,CakePHP 允许您通过 Bake 控制台以这种方式创建管理功能。
您可以在 AppController 中通过几行简单的代码来保护所有以 admin_ 为前缀的控制器功能,并且所有管理功能都可以通过整洁、一致的 URL 访问,如下所示:http ://www.example.com/admin/my_controller/my_function
这应该让你开始:http ://book.cakephp.org/2.0/en/development/routing.html#prefix-routing
如果您需要更多帮助,请告诉我,我会用更多信息更新我的答案。
编辑:更多信息...
以下是设置管理员路由的一些步骤:
1/ 在 app/Config/core.php 的第 113 行附近,确保该行存在且未注释:
Configure::write('Routing.prefixes', array('admin'));
2/ 在 app/Controller/AppController.php(即控制器超类)中,在 beforeFilter 方法中测试管理路由。不要在每个控制器的 beforeFilter 中这样做——这不符合 DRY 原则。下面以我的前置过滤方法为例:
function beforeFilter() {
if (isset($this->request->params['admin'])) {
// the user has accessed an admin function, so handle it accordingly.
$this->layout = 'admin';
$this->Auth->loginRedirect = array('controller'=>'users','action'=>'index');
$this->Auth->allow('login');
} else {
// the user has accessed a NON-admin function, so handle it accordingly.
$this->Auth->allow();
}
}
3/ 使用 admin_ 为所有管理功能添加前缀,它们应该可以通过前缀路由自动使用。
例如。
function admin_dostuff () { echo 'hi from the admin function'; } // This will be available via http://www.example.com/admin/my_controller/dostuff
function dostuff () { echo 'hi from the NON-admin function'; } // This will be available via http://www.example.com/my_controller/dostuff
一旦你完成了设置,你需要做的就是在管理函数前面加上 admin_ 前缀,Cake 会为你处理这一切。有道理?
编辑2:
这是一些快速编写的示例代码,可以帮助您解决问题。
function beforeFilter() {
if (isset($this->request->params['admin'])) {
// the user has accessed an admin_ function, so check if they are an admin.
if ($this->Auth->user('user_type') == 1){
// an Admin user has accessed an admin function. We can always allow that.
$this->Auth->allow();
} else {
// A non-admin user has accessed an admin function, so we shouldn't allow it.
// Here you can redirect them, or give an error message, or something
}
} else {
// the user has accessed a NON-admin function, so handle it however you want.
$this->Auth->allow(); // this example gives public access to all non-admin functions.
}
}