Cakephp 使用一个控制器模型中的枚举在另一个控制器模型中进行逻辑检查
我有以下代码Cakephp 使用一个控制器模型中的枚举在另一个控制器模型中进行逻辑检查,cakephp,Cakephp,我有以下代码 class PostsController extends AppController { public function approve($id = null, $user = true ) { if (!$id) { throw new NotFoundException(__('Invalid article')); } $post = $this->Post->findById(
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']
),它是一个枚举,来指定操作的作用。然而,我似乎无法让这个工作
我是否需要做一些不同的事情来确保它知道控制器需要使用用户模型?在您的
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') {
// ...
}
从哪里获得
$user
变量?通常,您必须从会话$user=$this->Session->read('Auth.user')获取它代码>我在AppController中设置了它,我以为它会级联下来。当我在视图中回显$current_user[role]或$user[role]时,我得到了正确的值,但这在控制器函数中为什么不起作用呢?事实上,使用Auth
应该是goYes的方法,Auth更容易,更有意义。但是如果他想向所有控制器发送其他数据,他可以使用AppController