0

I am currently using the codeigniter tank_auth, at the start of every controller method I have to do the following:

$data['profile'] = $this->tank_auth->get_profile();

The main reason I do this is to display the current logged in username, and also get their privilege level.

I am going over the code trying to go by the DRY principle and have moved a lot of repeated code over to the _constructor method (Like checking if the user is logged in). I am just wondering if there is a way to move this code from the start of every method to the constructor.

My current constructor method looks like so:

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

    // If the user isn't logged in redirect to login page.
    if (!$this->tank_auth->is_logged_in())
        redirect('auth/login');

  }

Thanks!

2 Answers 2

1

Add variable $data to the controller and use it for all your view data. For example:

public function __construct()
{
    parent::__construct();
    $this->data['profile'] = $this->tank_auth->get_profile();
}

When calling the view remember to call it like this:

$this->load->view('my_view', $this->data);
Sign up to request clarification or add additional context in comments.

4 Comments

Hey thanks for the reply, if I do it this way how would I pass data to the view from the controller ?
Thats in the second code snippet: $this->load->view('my_view', $this->data);
Thanks thats it! Although I needed to change all other vars from $output['title'] = "Bla bla"; to $this->output['title'] = "Bla bla";
Indeed. It is a big change but it helps keeping the code DRY.
1

You can also extend CI_Controller with MY_Controller and put the login check in the constructor of MY_Controller. Just extend all controllers which need this check from MY_Controller instead of CI_Controller.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.