我是Code Igniter的新手,我正在构建自己的用户系统。我目前正在登录过程中,我已经检查了用户当前是否登录。
在我的标题中,我想要显示“已注销”的链接(如果他们已经登录),或者“登录”(如果他们当前未登录)。
我的索引控制器中有一个工作函数,如下所示,$ loginstatus变量被发送到我的页面标题视图:
function check_session()
{
//Check session status
$session = $this->session->userdata('login_state');
$default = "Log In";
if ($session == 1)
{
$url = site_url('index.php/users/logout');
$status = "Log Out";
}
else
{
$url = site_url('index.php/users/login');
$status = $default;
}
$loginstatus = array(
"url" => $url,
"status" => $status
);
return $loginstatus;
}
因为它当前只在索引控制器中,所以没有为其他页面的标题视图生成$ loginstatus,这是我的问题。
我将把这个函数放在哪里,以便它总是在我的标题之前加载?我尝试使用'Common'类创建一个库,然后自动加载,但我最终遇到了很多问题。
提前致谢。
答案 0 :(得分:8)
如果您正在使用CI版本bellow 2.0,那么在application / libraries / MY_Controller.php中创建新类,否则在application / core / MY_Controller.php中,所有应用程序控制器都应该从它扩展。在__construct方法的这个类中,您将检查登录状态并将其发送到视图。
class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); //Get the status which is array $login_status = $this->check_session(); //Send it to the views, it will be available everywhere //The "load" refers to the CI_Loader library and vars is the method from that library. //This means that $login_status which you previously set will be available in your views as $loginstatus since the array key below is called loginstatus. $this->load->vars(array('loginstatus' => $login_status)); } protected function check_session() { //Here goes your function } }
还要确保您的应用程序控制器从此类扩展
//application/controllers/index.php class Index extends MY_Controller { public function __construct() { parent::__construct(); } }
在您的观看中,您可以这样做: < a href =“<?php echo $ loginstatus ['url'];?>”><?php echo $ loginstatus ['status']; ?>< / A>
这是可能的,因为CI_Loader vars()方法正在对传递给它的参数执行extract。