2011-11-24 110 views
7

让说我叫控制器时,我有很多方法,如 get_book();read_book();remove_book();笨 - 如何检查会议在每一个方法

类中的任何方法可以在没有用户使用登录后,我可以从会话中获得user_id

我的问题是,什么是最好的方法来检查user_id会话是否设置,以便我可以使用这些方法?

至于现在我想建立一个is_logged_in()方法,并将其与if-else语句适用于每一个方法,如

if($this->is_logged_in() 
{ 
    //do something 
} 
else 
{ 
    //redirect to home 
} 

是不是很漫长而乏味?有没有最终的方法来实现这一目标?

我读的链接

codeigniter check for user session in every controller

但似乎还是有在每一个方法来应用is_logged_in检查。

谢谢你帮助我!

回答

11

创建一个名为MY_controller.php(前缀可以在配置文件中编辑)在/application/core文件:

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class MY_Controller extends CI_Controller { 


    function __construct() 
    { 

     parent::__construct(); 

     //Initialization code that affects all controllers 
    } 

} 


class Public_Controller extends MY_Controller { 

    function __construct() 
    { 
     parent::__construct(); 

     //Initialization code that affects Public controllers. Probably not much needed because everyone can access public. 
    } 

} 

class Admin_Controller extends MY_Controller { 

    function __construct() 
    { 
     parent::__construct(); 
     //Initialization code that affects Admin controllers I.E. redirect and die if not logged in or not an admin 
    } 

} 

class Member_Controller extends MY_Controller { 

    function __construct() 
    { 
     parent::__construct(); 

     //Initialization code that affects Member controllers. I.E. redirect and die if not logged in 
    } 

} 

然后,无论何时您创建新控制器,您都可以决定需要什么访问权限

class Book extends Member_Controller { 

     //Code that will be executed, no need to check anywhere if the user is logged in. 
     //The user is guaranteed to be logged in if we are executing code here. 

//If you define a __construct() here, remember to call parent::__construct(); 
    } 

这很大程度上减少了代码重复,因为如果您需要除Book以外的其他成员控制器,则只需扩展Member_Controller即可。而不是必须在他们所有人中进行检查。

+0

我明白你的答案,这是真的遵循DRY并帮助我将正确的业务规则应用于不同的用户组。非常感谢您和@Kemal Kernal的帮助:) – user826224

9

你不一定需要那样做。只需将登录检查代码放入构造函数中,即可完成设置!

class Book extends CI_Controller 
{ 
    public function __construct() 
    { 
     if ($this->is_logged_in()) 
     { 
      // redirect to home 
     } 
    } 

    public function get_book() 
    { 
     ... 
    } 

    // The rest of the code... 
} 
+0

非常感谢你,我测试过,它完美无瑕。要从链接更新,我们应该把MY_Controller放在application/core下。再次感谢您的帮助:)祝您有美好的一天! – user826224

+2

@ user826224,你仍然需要用这个复制代码。我的答案与你链接的答案有很大的不同,你应该仔细阅读:) – Esailija

0

可以在控制器的构造函数中使用的方法,如:

 
if (! $this->session->userdata('logged_in')) 
    { 
      redirect('login'); 
    }