ignite1688846
ignite1688846

Reputation: 147

Codeigniter: HELPERS and $CI =& get_instance();

I have a few functions that manage the access levels of a certain controllers within the controller file.

I decided to take them out either to a library or to a helper.

Since they are mostly procedural I decided to use helpers.

Here is the original method in the controller file (others are access_level_member, access_level_moderator etc)

  function access_level_admin() {

    if (!$this->session->userdata('loggedin')) {
        $this->session->set_flashdata('warning', 'Not logged in.');
        redirect('/start_page', 'refresh');
    }
    if (!$this->session->userdata('admin')) {
        $this->session->set_flashdata('warning', 'Access Denied!');
        redirect('/start_page', 'refresh');
    }  

Here is it withing a helper.

function access_level_admin() {
    $CI =& get_instance();
    if (!$CI->session->userdata('loggedin')) {
        $CI->session->set_flashdata('warning', 'Not logged in.');
        redirect('/start_page', 'refresh');
    }
    if (!$CI->session->userdata('admin')) {
        $CI->session->set_flashdata('warning', 'Access Denied!');
        redirect('/start_page', 'refresh');
    }  

So my question is, is it a better idea to place it in a library or a helper and is it ok to use $CI =& get_instance(); within a helper.

Any better ideas or recommendations?

Upvotes: 2

Views: 6683

Answers (1)

Stanley
Stanley

Reputation: 5127

I would place the logic in a parent controller and have your controllers extend it.

class Authenticated_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('loggedin')) {
            $this->session->set_flashdata('warning', 'Not logged in.');
            redirect('/start_page', 'refresh');
        }
}

class Admin_Controller extends Authenticated_Controller {
    public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('admin')) {
            $this->session->set_flashdata('warning', 'Access Denied!');
            redirect('/start_page', 'refresh');
        }
}

Upvotes: 3

Related Questions