Welcome Guest, Not a member yet? Register   Sign In
Beginner: Creating a User Model
#1

[eluser]matt_a[/eluser]
I've seen plenty of tutorials out there on creating a User model, and they're all great. I've encountered an issue that I can't seem to find a solution for, though: when a user is attempting to create a new account.

I obviously want to check to make sure the same username isn't already in the database, but I also want to make sure the email address isn't either. In my User model, I've created a function called _user_exists(),

Code:
function _user_exists($attribute, $value)
     {
         $this->db->where($attribute, $value);
         $result = $this->db->get('users');
         return $result->num_rows() > 0;
     }

and I call this function on the username and email provided in a create() function. My problem is generating the correct error message to display to the user (username is already in use or someone already registered with that email address). I don't know the best way to do this. I have a few ideas though..

1) create a variable, say $message, and set it appropriately. then load a view and pass it $message (is it ok to load a view from a model, though?)

Any suggestions?
#2

[eluser]Sean Gates[/eluser]
I would handle the message in the controller. The rule of thumb is to keep text/html/content out of the model because it is just for data transport and minor application logic. Therefore, you can do whatever you need to in the controller before you send it to the view, keeping logic in the controller, and presentation in the view.

Hope that helps.
#3

[eluser]matt_a[/eluser]
Thanks for the reply. I'll just continue writing the read method and call this in the controller. Thanks again!
#4

[eluser]WanWizard[/eluser]
The logical place to do this is in a form validation callback.

The new user posts the registration form, you run your validation rules, and if the form doesn't validate, return to the form with the generated error messages. This is all functionality of the form validation library, no need to invent your own logic.
#5

[eluser]Sean Gates[/eluser]
Right, but the validation callback would still call the model (database query), correct?
#6

[eluser]WanWizard[/eluser]
Depends on how you code your application, but since callbacks need to be in the controller that runs the validation, it's logical to call a model method to fetch the user data.
#7

[eluser]Sean Gates[/eluser]
Yup, I think we're in agreement here. Cool.

So, to recap, create a validation callback, and in the callback call the model method.

Good luck!
#8

[eluser]matt_a[/eluser]
Thanks a lot guys, I appreciate your help!




Theme © iAndrew 2016 - Forum software by © MyBB