【问题标题】:CodeIgniter always run this codeCodeIgniter 总是运行这段代码
【发布时间】:2011-11-02 20:11:47
【问题描述】:

我需要在每个请求上运行一些代码,始终取决于用户是否登录。

我把这段代码放在哪里?

有没有可能我可以传递数据,这段代码:

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

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->library('security');
        $this->load->library('tank_auth');
        $this->lang->load('tank_auth');
        $this->load->model('users_model');

        if ($this->tank_auth->is_logged_in())
        {
            $data = $this->users_model->get_userinfo($this->tank_auth->get_username());

            if ($data['exp'] >= $data['max_exp']) {

                $new_data = array(
                    'exp' => $data['exp'] - $data['max_exp'],
                    'level' => $data['level'] + 1,
                );

                $this->db->where('id', $data['id']);
                $this->db->update('users', $new_data);

                echo 'Hello?';
            }
        }
    }

这是核心类中的 MY_Controller。我可以进一步传递这些数据吗?我想,在真正的课堂上重新抓取所有数据,感觉没有必要。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    在核心文件夹下创建一个类,然后让所有控制器扩展该类。

    我做了一个与你描述的非常相似的登录系统。

    这是核心文件夹中的一个类:

    class MY_Controller extends CI_Controller{
        public function __construct()
        {
            parent::__construct();
            $this->load->library('cart');
            $this->load->library('session');
            $this->load->library('pagination');
    
            $this->load->helper('form');
            $this->load->library('form_validation');
            if (!$this->session->userdata('loggedin')){
                redirect('/sessions/log_in/','refresh');
            } 
        }
    }
    

    注意:确保您的配置正确设置为继承前缀

    那么控制器文件夹中的控制器将扩展 My_Controller

    有关分层登录或更详细的示例,请参阅我的旧问题:

    Codeigniter: Controlling log in privileges with inheritance

    还有我的东西基于的教程:

    http://davidwinter.me/articles/2009/02/21/authentication-with-codeigniter/

    关于进一步传递数据的答案: 使用会话类?

    http://codeigniter.com/user_guide/libraries/sessions.html

    $this->load->library('session');
    $this->session->userdata('fieldName') = 1;//*appropriateValue*;
    //Call this in another class
    echo $this->session->userdata('fieldName');
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2023-03-18
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多