Welcome Guest, Not a member yet? Register   Sign In
Accessing functions from external controllers
#1

[eluser]sjmiller85[/eluser]
What I would like to do is access a function from another controller than the one that is being called. To put this into context, I'll explain what I'd like to do specifically:

In the constructor for each controller, I have a call to my database being made to compare a cookie containing log-in information to verify whether the person is logged in or not, based off the cookie. Instead of attaching this bit of code to each constructor of each controller, it would be convenient if I could just create a function in a controller somewhere, and call to that function in each controller's constructor rather than typing it out in every controller.

Any ideas? Thanks for the help!
#2

[eluser]Thorpe Obazee[/eluser]
You can extend the Controller via: MY_Controller

Code:
class MY_Controller extends Controller {

    function MY_Controller()
    {
        parent::Controller();



            if ( ! $this->auth->logged_in(array('login', 'admin')))
            {
                $this->session->set_flashdata('message', 'You do not have access to view this page');

                redirect('admin/test/users/login');
            }

    }
}

http://ellislab.com/codeigniter/user-gui...asses.html
#3

[eluser]sjmiller85[/eluser]
Ah! So if I place whatever constructor I want in MY_Controller, it will automatically get executed in any controller that ever gets executed? Nifty!

Now lets say I wanted to create functions in MY_Controller, how would I access those functions in my controllers?
#4

[eluser]Thorpe Obazee[/eluser]
Code:
// MY_Controller
class MY_Controller extends Controller {

    function MY_Controller()
    {
        parent::Controller();

    }

    function something_else()
    {
         // do something
    }
}
Code:
// controller
class Front extends MY_Controller {

    function Front()
    {
        parent::MY_Controller();
    }

        function do_something()
        {
              $this->something_else();
        }
        
}

$this->something_else() is from the MY_Controller.
#5

[eluser]sjmiller85[/eluser]
Awesome! Thank you very much for your assistance!!
#6

[eluser]sjmiller85[/eluser]
That's odd. I've created MY_Controller in the application/libraries folder and given it nothing but a constructor at the moment. Yet when I go through my controllers and change them to extend MY_Controller, it doesn't seem to be executing the constructor in the MY_Controller class.
#7

[eluser]JoostV[/eluser]
Did you tell you new controller to execute it's parent's constructor?
Code:
function __construct()
{
    // Call parent::__construct(); or parent::MY_Controller();, depending on
    // how you named the constructor in the parent calss
    parent::__construct();
}




Theme © iAndrew 2016 - Forum software by © MyBB