Possible Duplicate:
echo user in view from sessions code igniter
I don’t want to define and store the user in every controller and then pass it to the view.
Here’s my controller:
Login controller:
class LoginController extends CI_Controller {
function index(){
$new['main_content'] = 'loginView';
$this->load->view('loginTemplate/template', $new);
}
function verifyUser(){
//getting parameters from view
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$this->load->model('loginModel');
$query = $this->loginModel->validate($data);
if ($query){
//if the user c validated data variable is created becx we want to put username in session
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('sessionController/dashboard_area');
}else{
$this->index();
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
?>
My controller, which I’ve stored in core folder, so now every controller now extends this controller. I think this controller can be customize so I can access the user in every view page which extended this controller:
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
$this->is_logged_in();
}
function dashboard_area(){
$data['main_content'] = 'dashboardView';
$this->load->view('dashboardTemplate/template', $data);
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.';
redirect('loginController');
}
}
}
?>
Here is my simple one member controller which extended the above controller:
Here in index function I am storing the username and then pass into the view which I don’t want to do:
class CategoryController extends MY_Controller {
function index(){
$data['main_content'] = 'categoryView';
$username= $this->session->userdata('username');
$data['username']=$username;
$this->load->view('dashboardTemplate/template',$data);
}
You can just call
$this->session->userdata('username')in your view.It is stored in the session, so you do not have to pass it to the views from the controller.
UPDATE PER COMMENT;
if you want to load a view depending on the base controller (eg user), I would use a template library and set the template to use in the construct of the base controller.
For example (using this template library);