我正在使用CakePHP制作一个系统,其中用户可以是a、B或C。比如学生、老师和其他角色。有可能让他们都通过1个链接登录吗?所以不是/学生/登录和/教师/登录,而是像www.somewebsite/login这样的东西?
阅读本教程,它完全涵盖了您的要求。另请阅读本节。
为不同类型的用户提供不同的控制器是没有任何意义的,你只会重复代码。如果你需要根据角色采取不同的操作,你可以在你的登录方法中这样做,从你的登录()方法中调用另一个方法,比如afterStudentLogin(),并在那里做特定于角色的事情。原因是一个方法应该总是只做一个任务,所以您可以在一个单独的方法中将特定于角色的代码与其解耦。
public function login() {
if ($this->Auth->user()) {
/* ... */
$callback = 'after' . $this->Auth->user('role') . 'Login');
$this->{$callback}($this->Auth->user());
/* ... */
}
}
即使用户类型非常不同,它们也会共享一个共同的东西:登录。在这种情况下,有一个用户表,例如student_profils
表和teacher_profiles
表。如果区别只是几个字段,我会把它们都放在一个表中,比如profiles
。
如果您希望使用/login而不是/users/login,则应该使用路由。
Router::connect(
'/login',
array(
'controller' => 'users',
'action' => 'login'
)
);
你也可以看看这个用户插件,它涵盖了许多常见的与用户相关的任务。这里有一个简单的多角色授权适配器。
根据用户组的不同,一个简单的基本登录功能如下所示
<?php
public function login() {
//if user already logged in call routing function...
if($this->Session->read('Auth.User')) {
$this->routing();
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
//if user status is active...
if ($this->Auth->user('status') == 1){
//redirect users based on his group id...
if($this->Auth->User('group_id')==1){
$this->redirect($this->Auth->redirect('/admins/dashboard'));
}
else if($this->Auth->User('group_id')==2){
$this->redirect($this->Auth->redirect('/teachers/dashboard'));
}
else if($this->Auth->User('group_id')==3){
$this->redirect($this->Auth->redirect('/students/dashboard'));
}
}
else{
$this->Session->delete('User');
$this->Session->destroy();
$this->Session->setFlash('Your account is not yet activated. Please activate your account to login.', 'warning');
}
}
else {
$this->Session->setFlash('Your username or password was incorrect.', 'error');
}
}
}
//just route the loggedin users to his proper channel...
public function routing() {
if($this->Session->read('Auth.User.Group.id') == 1) {
$this->redirect('/admins/dashboard');
}
else if($this->Session->read('Auth.User.Group.id') == 2) {
$this->redirect('/teachers/dashboard');
}
else if($this->Session->read('Auth.User.Group.id') == 3) {
$this->redirect('/students/dashboard');
}
else {
$this->Session->destroy();
$this->redirect('/');
}
}
?>