John
John

Reputation: 3050

CodeIgniter always run this code

I need to run a few code on every request, always depending on If the user is logged in or not.

Where do I put this code?

Is there any possibility I can pass the data, This code:

 public function __construct()
    {
        parent::__construct();

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->library('security');
        $this->load->library('tank_auth');
        $this->lang->load('tank_auth');
        $this->load->model('users_model');

        if ($this->tank_auth->is_logged_in())
        {
            $data = $this->users_model->get_userinfo($this->tank_auth->get_username());

            if ($data['exp'] >= $data['max_exp']) {

                $new_data = array(
                    'exp' => $data['exp'] - $data['max_exp'],
                    'level' => $data['level'] + 1,
                );

                $this->db->where('id', $data['id']);
                $this->db->update('users', $new_data);

                echo 'Hello?';
            }
        }
    }

This is MY_Controller, in the Core class.. Can I pass this data further? I guess, regrabbing all data, over again in the real class, feels unneccerary.

Upvotes: 3

Views: 1906

Answers (1)

Zigu
Zigu

Reputation: 1665

Create a class under the core folder then make all your controllers extend that class.

I did a log in system very similar to what you are describing.

This is a class in the core folder:

class MY_Controller extends CI_Controller{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('cart');
        $this->load->library('session');
        $this->load->library('pagination');

        $this->load->helper('form');
        $this->load->library('form_validation');
        if (!$this->session->userdata('loggedin')){
            redirect('/sessions/log_in/','refresh');
        } 
    }
}

Note: make sure your config is correctly set up for inheritance prefix

Then your controllers in the controller folder will extend My_Controller

For tiered log-ins or a more detailed example see my old question:

Codeigniter: Controlling log in privileges with inheritance

Also the tutorial I based my stuff off of:

http://davidwinter.me/articles/2009/02/21/authentication-with-codeigniter/

Answer in regards to passing data further: Use the session class?

http://codeigniter.com/user_guide/libraries/sessions.html

$this->load->library('session');
$this->session->userdata('fieldName') = 1;//*appropriateValue*;
//Call this in another class
echo $this->session->userdata('fieldName');

Upvotes: 6

Related Questions