Skip to content

Anatomy of a controller

bbalet edited this page Mar 29, 2014 · 1 revision

This page explains how to add your controller by respecting the way the application has been developed

Constructor

The constructor (except session controller) checks if the user is connected to the application. If the user is not connected, it redirects to login page. Otherwise it loads some private properties such as :

  • Data about the user that can be used in view (fullname, etc.)
  • Privilege of the user for the access logic.

public function __construct() {
parent::__construct();
//Check if user is connected
if (!$this->session->userdata('logged_in')) {
$this->session->set_userdata('last_page', current_url());
redirect('session/login');
}
$this->load->model('users_model');
$this->fullname = $this->session->userdata('firstname') . ' ' .
$this->session->userdata('lastname');
$this->is_admin = $this->session->userdata('is_admin');
$this->user_id = $this->session->userdata('id');
}

getUserContext

This function prepares data to be passed to the menu view such as the user fullname.


private function getUserContext() {
$data['fullname'] = $this->fullname;
$data['is_admin'] = $this->is_admin;
$data['user_id'] = $this->user_id;
return $data;
}

Typical action

  • A typical action starts by checking is the user can accessed to the function. This function level security check is performed by auth library. However, the check performed into auth library is very basic (based on the role of the user and the ownership of the manipulated object). Additional access logic should be added for more complex access rules.
  • Remaining code relies on CI framework.

public function index() {
$this->auth->check_is_granted('list_users');
$data = $this->getUserContext();
$data['users'] = $this->users_model->get_users();
$data['title'] = 'Users';
$this->load->view('templates/header', $data);
$this->load->view('menu/index', $data);
$this->load->view('users/index', $data);
$this->load->view('templates/footer');
}