CodeIgniter Model and Controller and UserID

My models in CodeIgniter should check if the user is allowed to perform this action. Inside the models, I referenced using $ this-> session-> userdata ['user_id'].

My question is: should I set a variable in $ this-> session-> userdata ['user_id'] in the Controller and pass it to the Model or just check it inside the Model?

Does it even matter? I assume that passing the $ user_id function to the function will make it (slightly) more readable. What are the arguments and recommendations for / against?

+4
source share
2 answers

You can choose between data that is fundamental to your application and data that is random for a given member function of the model. Things that you use everywhere should be guaranteed (basic elements, globals, etc.), and things used only in the current function should be parameters. You will find that using implied variables (e.g. $this->session->userdata ) in many places in your models and views will quickly become spaghetti and will be unpredictable if you do not load them correctly.

In my CodeIgniter projects, I add a custom base model and controller that inherit the CI structure, adding my own member data, which is used throughout the application. I use these base classes to provide data and functions that all my models and controllers use (including things like userID ). In the constructor my_base_controller I call the base CI constructor and configure the data that all my controllers and views need. This ensures predictable defaults for class data.

+6
source

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

In code, 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 foo() functions requires authentication .. I would do this

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

_checkAuthentication() can be simplified, for example:

 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; } } 
+1
source

All Articles