Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter - should I access session data in a view?

Should I grab some data from a session variable for my header from the header which needs to display a few details for the user currently logged in. Or, in each controller, load user data then send it to the corresponding view? Seems like I should do it from the controllers but having it in header requires less code.

like image 261
el_pup_le Avatar asked Apr 07 '26 02:04

el_pup_le


1 Answers

Should you? For the sake of maintainability and honoring the MVC pattern, I would say do it in the controller, I don't think one line of code is going to be an issue, you can get it all like this:

$data['userdata'] = $this->session->all_userdata(); // returns and associative array

Then pass that to the view, and get the stuff out in the view with $userdata['whatever'] which is the same amount of code as getting it from the header anyway.

The function is located here


Edit - 03 November 2015

As of version 3.0 $this->session->all_userdata(); has been depreciated. Instead directly accessing the $_SESSION object directly is the prefered method, however $this->session->userdata(); with no parameters could be used with older applications.

$data['userdata'] = $_SESSION; // returns and associative array

or

$data['userdata'] = $this->session->userdata();

Documentation on userdata():

Gets the value for a specific $_SESSION item, or an array of all “userdata” items if not key was specified.

NOTE: This is a legacy method kept only for backwards compatibility with older applications. You should directly access $_SESSION instead.

like image 105
Cubed Eye Avatar answered Apr 08 '26 16:04

Cubed Eye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!