1

这是一个更多的意见问题,而不是特定问题的解决方案。

我是第一次使用 CakePHP,现在正在处理网站的管理部分。

作为 MVC 或 CakePHP 开发人员,您喜欢将管理功能放在哪里?

最初我将它们放在一个 AdminController 中,但后来更改为将函数放在一个控制器中,该控制器适用于被操作的数据类型。例如,我将用户列表/编辑放在 UserController 中。

对我来说,这更有意义,因为 UserController 中可能有可能有用的功能。

如果你留下回应,你能留下几句话说为什么吗?也许这是一个有争议的问题。

保重,李

- 编辑

if ($this->Auth->user('user_type') == 1){//double-check the user is Admin
            $this->Auth->allow('display');
            $this->Auth->allow('watch');
4

1 回答 1

10

我不认为这是一个有争议的问题。将管理功能放在它们各自的控制器中(即,不是全部放在一个“管理”控制器中),并使用 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.
    }
}
于 2012-07-04T07:38:16.233 回答