Welcome Guest, Not a member yet? Register   Sign In
A function in all controlers
#1

[eluser]kosmosik[/eluser]
I have a block of code that I wan't to run inside every controller. It is auth/ACL functionality I don't wan't to repeat this block in each controller so where to put this code?
#2

[eluser]Neophyte[/eluser]
you could use a pre_controller hook to have code run before every controller ?
#3

[eluser]ontguy[/eluser]
Michael Wales has a nice suggestion for this; http://www.michaelwales.com/2008/01/my-c...-dev-pack/. There are a few posts in the forum with some examples; I can't find now so I'll just paste how I got his method working.

application\libraries\MY_Controller.php
Code:
class Public_Controller extends Controller {
    function Public_Controller() {
        parent::Controller();
        $this->load->library('auth');
        $this->data->user = $this->auth->get_user($this->session->userdata('user_id'));
    }
}

class Auth_Controller extends Public_Controller {
    function Auth_Controller() {
        parent::Public_Controller();
        if ($this->data->user === FALSE) {
            redirect('admin/login');
        }
    }
}

application\controllers\checkout.php
Code:
class Checkout extends Auth_Controller {
  function __construct() {
        parent::Auth_Controller();
    }
//more code
}

application\controllers\admin.php
Code:
class Admin extends Public_Controller {
  function __construct() {
        parent::Public_Controller();
    }
    
    function login () {
        //load logon form, validation, set session, etc.
        redirect ('checkout');
        }




Theme © iAndrew 2016 - Forum software by © MyBB