3

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.

1
  • 1
    Any time you can accomplish something in one place, rather than repeating it in every controller, then you should do it. Commented Oct 2, 2011 at 3:15

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Accessing session data from the view does not dis-honor MVC. The session data is available to the views, so why load it via the controller? I think DRY (Don't Repeat Yourself) trumps MVC in this situation.
Agreed with @permawash. Since data is already available, assigning & retrieving it again sounds inefficient to me & may be also prone to unwanted errors
@Cubed Eye Don't you mean one line of code in each controller? Anyway, I'm going to load it from the view.
I agree with @permawash. There are so many 'rules' to follow in MVC and some don't really make sense. If you can do it once, then do it. No sense in having to put that in every controller. For the purists out there, you could create a common controller that extends CI_Controller, make your $data variable a class variable, and add session data to your $this->data variable in the constructor. Then, extend your common controller in your various other controllers.
all_userdata IS DEPRECIATED.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.