Reputation: 147
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
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