使用来自一个控制器模型的枚举进行另一个控制器模型中的逻辑检查

时间:2014-02-16 16:03:46

标签: cakephp

我有以下代码

class PostsController extends AppController {

    public function approve($id = null, $user = true ) {
        if (!$id) {
            throw new NotFoundException(__('Invalid article'));
        }

        $post = $this->Post->findById($id);
        if(!$post) {
            throw new NotFoundException(__('Invalid article'));
        }

        if ($user['role'] == 'moderator') {
            $this->Post->saveField("approval",'Approved by Moderator');
        }
        elseif ($user['role'] == 'admin') {
            $this->Post->saveField("approval",'Posted!');
        }
        $this->redirect(array('action'=>'index');
    }
}

我正在尝试使用当前用户的“角色”($user['role'])(这是一个枚举)来指示操作的作用。但是,我似乎无法让这个工作。

我是否必须采取不同的措施以确保它知道控制器需要使用用户模型?

1 个答案:

答案 0 :(得分:2)

AppController中,您似乎有类似

的内容
$this->set('user', $user);

您还应该添加

public $loggedUser;

然后

$this->loggedUser = $user;

这样,您将loggedUser发送给所有控制器。

PostsController中,您需要

if ($this->loggedUser['role'] == 'moderator') {  
     // ..
}

请注意,您可以使用

轻松处理任何控制器内的已记录用户信息
$this->Auth->user();

你可以拥有

if $this->Auth->user('role') == 'moderator')  {
    // ...
}

http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user

相关问题