Welcome Guest, Not a member yet? Register   Sign In
Redundant Code
#1

[eluser]insub2[/eluser]
If I have a method in a model that is only suppose to be called from a controller that is limited to only logged in users, is it considered bad practice to assume that there will always be a user id in the session database?

Suedo Code:
Code:
Write Controller

function index()
{
   if (user === logged in)
   {
      $this->write_model->insert($_POST);
      $this->load->view('success');
   }
   else
   {
      $this->load->view('error');
   }
}

...and...
Code:
Write Model

function insert($data)
{
   // Set $data['userID']
   $data['userID'] = $this->db_session->userdata('userID');

   $this->db->insert($this->_reviews, $insert);
}


Or should I have some sort of failsafe in the model? Something like:
Code:
Write Model

function insert($data)
{
   // Set $data['userID']
   if ($data['userID'] = $this->db_session->userdata('userID'))
   {
      $this->db->insert($this->_reviews, $insert);

      return TRUE;
   }

   return FALSE;
}
#2

[eluser]bretticus[/eluser]
It is probably bad practice to validate users in your model period.

Why not validate in the controller before you call the model method like in your first example?
#3

[eluser]bretticus[/eluser]
Ah, I get the point finally, you don't want to have to call the login logic for each method that calls write under that model.

I would still keep the login logic out of the model. It's never good practice to put user web logic in your data tier. It just keeps your code more modular which is kinda the point of MVC in the first place.

I would use a MY_Controller (extend Controller) to incorporate your login logic. There are many examples in this forum and on Google that specify how to do it.
#4

[eluser]insub2[/eluser]
Sorry, I forgot to explain that the userID is set in the model from the session data. It is not sent to the model from the controller.

The validation is in the controller. The second version of the model is making sure there is a userID *in case* the model gets called without having a logged in user. If there isn't a userID set, I'll get a database error. It just seems like it may be a good idea to protect against that (unlikely) scenario.




Theme © iAndrew 2016 - Forum software by © MyBB