Codeigniter构造函数-检查用户是否已登录


Codeigniter constructor - check if user is logged in

我正在尝试为我的控制器创建一个构造函数,该构造函数引用了我在自动加载的helper中包含的函数。

函数检查用户是否已登录,如果已登录,则将其重定向到登录页面。

似乎我没有正确设置结构,因为我收到以下错误:

Fatal error: Call to undefined method Profile::is_logged_in()

这是控制器:

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Profile extends CI_Controller {
       public function __construct()
       {
            parent::__construct();
            //function inside autoloaded helper, check if user is logged in, if not redirects to login page
            $this->is_logged_in();
       }
    public function index() {
    echo 'hello';
    }
} 

我只想在用户登录时使控制器内的功能可访问。

这是自动加载的帮助器

$autoload['helper'] = array('url','array','html','breadcrumb','form','function','accesscontrol');

(accesscontrol_helper.php):

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    function is_logged_in()
    {
        $is_logged_in = $this->session->userdata('is_logged_in');
        if(!isset($is_logged_in) || $is_logged_in != true)
        {
            echo 'You don''t have permission to access this page. <a href="../login">Login</a>';    
            die();      
            //$this->load->view('login_form');
        }       
    }

为什么我不能运行这个函数?在helper中包含代码是最好的方法吗?

正如前面提到的,帮助程序只是函数的集合。扩展它们:

  • 因为它们有时被加载不止一次,所以你需要指定不声明一个已经存在的函数,否则你会引发一个错误。
  • 此外,如果不首先实例化主CI对象,则不能在它们中调用CI的类。这是使用辅助函数的一种更合适的方式:

    if(!function_exists('is_logged_in'))    
    {
        function is_logged_in()
        {
        $CI =& get_instance();
        $is_logged_in = $CI->session->userdata('is_logged_in');
           if(!isset($is_logged_in) || $is_logged_in != true)
           {
            echo 'You don''t have permission to access this page. <a href="../login">Login</a>';    
            die();      
           }       
        }
    }
    

我也会让它返回而不是echo,并将die()移动到控制器,但这是另一个故事。

helper只是包含函数,所以您不需要使用$this访问它。就像普通函数一样调用它:

is_logged_in();

您不使用$this调用辅助函数。只要做is_logged_in();

public function __construct()
{
    parent::__construct();
    //function inside autoloaded helper, check if user is logged in, if not redirects to login page
    is_logged_in();
}

accesscontrol_helper.php :

 <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 class Accesscontrol_helper{
 function is_logged_in()
 {
 //code
 }
 }
Profile controller:
class Profile extends CI_Controller {
       public function __construct()
       {
            parent::__construct();
            Accesscontrol_helper::is_logged_in();
       }
}