Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Controller function in another Controller in CodeIgniter

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

public function logged_user_only()
    {
        $is_logged = $this -> is_logged();
        if( $is_logged === FALSE)
        {
            redirect('user/login_form');
        }
    }

As this function calls another function called is_logged(), which just checks if the session is set, if yes it returns true, else returns false.

Now if i place this function in the begining of any function within same controller, it will check if the user is not logged, it will redirect to login_form otherwise continue. This works fine. For example,

public function show_home()
    {
        $this -> logged_user_only();
        $this->load->view('show_home_view');
    }

Now I would like to call this logged_user_only() function in a function of another controller to check if the user is logged in or not?

PS. If this can not be done, or is not recommended, where should i place this function to access in multiple controllers? Thanks.

like image 413
Roman Avatar asked Jul 11 '11 07:07

Roman


People also ask

How to use one controller function in another controller in CodeIgniter?

If you have functionality in controller A that you wish to use in controller B, then have B extend A, so that the function is then part of B. You mix up controllers and libraries. A library is a class with methods (functions) you can use in any controller where you load that library.

How can we call one controller function from another controller in PHP?

use App\Http\Controllers\OtherController; class TestController extends Controller { public function index() { //Calling a method that is from the OtherController $result = (new OtherController)->method(); } }


1 Answers

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

like image 117
simnom Avatar answered Sep 18 '22 06:09

simnom