开发者

CodeIgniter Model / Controller and UserID

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 variabl开发者_如何学运维e 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 ?


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.


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;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜