4

My Models in CodeIgniter need to check that a user is authorised to perform the given action. Inside the Models I have been referencing using $this->session->userdata['user_id'].

My question is - should I be setting a variable to $this->session->userdata['user_id'] in the Controller and passing this to the Model, or simply checking it inside the Model ?

Does it even matter ? I suppose passing $user_id into the function would make it (slightly) more readable. What are the arguements and recommendations for / against ?

2 Answers 2

6

You can choose between data that is fundamental to your application and data that is incidental to a given model member function. Things that you use everywhere should be guaranteed (base members, globals, etc.), and things used only in the current function should be parameters. You'll find that using implied variables (like $this->session->userdata) in many places in your models and views will become spaghetti quickly, and will be unpredictable if you don't bootstrap them properly.

In my CodeIgniter projects, I add a custom base model and controller that inherit from the CI framework, adding their own member data that is used everywhere in the app. I use these base classes to provide data and functions that all of my models and controllers use (including things like userID). In the constructor of my_base_controller, I call the CI base constructor, and set up data that all of my controllers and views need. This guarantees predictable defaults for class data.

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

1 Comment

+1 I do something similar with my base controller, since a userid is something that in most apps you'll be checking for everywhere.
1

Strictly speaking $this->session->userdata['user_id'] belongs to the controller.
Models deal with data only... controllers, by definition control the flow of the data...
and authentication is a form of data control... (IMHO)

Codewise, I follow this procedure

class MyControllerName extends Controller{
  function MyMyControllerName(){
    parent::Controller();
    $this->_user_id=$this->session->userdata['user_id']; //<-- define userid as a property of class
  }
}

And then, say one of my functions foo() requires authentication.. I would do this

function foo(){
  $this->_checkAuthentication(); //should short out if not authenticated
  //rest of the function logic goes here
}

the _checkAuthentication() can be simplistic like:

function _checkAuthentication(){
  if(!isset($this->_user_id) && $this->_user_id<=0){ /or any other checks
    header("Location: ".base_url()."location_of/user_not_authorised_page");
    exit;
  }
}

Comments

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.