Calling a Controller function in another Controller in CodeIgniter

后端 未结 4 1209
盖世英雄少女心
盖世英雄少女心 2020-12-06 06:10

I have a controller \"user\" in my codeigniter application. This controller has a function called logged_user_only():

public function logged_use         


        
相关标签:
4条回答
  • 2020-12-06 06:23

    just load user controller as library from your controller

    function __construct(){
         parent::__construct();
         $this->load->library('../controllers/user');
    }
    

    Now, call this function of user controller any where in your controller,

    $this->user->logged_user_only();
    
    0 讨论(0)
  • 2020-12-06 06:23

    Function login in Controller Login

    $data =array('username' => $this->input->post('username'), 'password' => $this->input >post('password')) $query = $this->db->get_where('usertable',$data)
        if ($query->num_rows() == 1) {
            $data = array(
                'username' => $this->input->post('username'),
                'logged_in' => TRUE,
                'role' => "user");
            $this->session->set_userdata($data);
            redirect('home');
        } 
    

    Function Construct in Controller user

    if ($this->session->userdata('logged_in') == TRUE && $this->session->userdata('role') == "user") {} else {redirect('home');}
    
    0 讨论(0)
  • 2020-12-06 06:26

    Calling a controller from another is not possible with CI and not recommended.

    Either move your logged_user_only into a helper or even better a core controller that you extend all of your controllers from (MY_Controller) see http://codeigniter.com/wiki/MY_Controller_-_how_to_extend_the_CI_Controller/

    0 讨论(0)
  • 2020-12-06 06:41

    Why not extend the controllers so the login method is within a MY controller (within the core folder of your application) and all your other controllers extend this. For example you could have:

    class MY_Controller extends CI_Controller {
        public function is_logged()
        {
            //Your code here
        }
    }
    

    and your main controllers could then extend this as follows:

    class Home_Controller extends MY_Controller {
        public function show_home()
        {
             if (!$this->is_logged()) {
               return false;
             }
        }
    }
    

    For further information visit: Creating Core System Classes

    New link is here: https://www.codeigniter.com/user_guide/general/core_classes.html?highlight=core%20classes

    0 讨论(0)
提交回复
热议问题