简体   繁体   中英

Moving methods out of Codeigniter controller

I got this in one of my Codeigniter controllers. But I would like it to be accessible to other controllers but I think $this keyword would have a different meaning, whilst it needs to refer to the controller that it is loaded into.

function checkSecurity($user, $page)
{
    if($this->mod_backend->canUserAccessPage($user, $page))
    {
        $this->load->view('header');
        $this->load->view($page, $data);
        $this->load->view('footer');       
    }
    else
    {
        $this->load->view('header');
        $this->load->view('unauthorised', $data);
        $this->load->view('footer');               
    }
}

If you need that a method will be accesible to all controllers in your app, you can implement a class in MY_Controller.php file and then all your controller must extend this class instead of CI_Controller .

For example in MY_Controller.php

<?php

class My_Controller extends CI_Controller{
    public function checkSecurity($user, $page)
    {
        if($this->mod_backend->canUserAccessPage($user, $page))
        {
            $this->load->view('header');
            $this->load->view($page, $data);
            $this->load->view('footer');       
        }
        else
        {
            $this->load->view('header');
            $this->load->view('unauthorised', $data);
            $this->load->view('footer');               
        }
    }

}

And then in your controller you must extend this class:

<?php

class Other_Controller extends My_Controller{
   //Do the stuff

   //You can call your function in every controller
   $this->checkSecurity('my_user', 'my_page');


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM