开发者

Where to validate and test user input date, In the controller or the model?

开发者 https://www.devze.com 2023-03-16 13:19 出处:网络
Where to clean up/ validat开发者_开发技巧e/ verify the user input data? In the controller or the model?In controller.

Where to clean up/ validat开发者_开发技巧e/ verify the user input data? In the controller or the model?


In controller.

Look at it this way: Your form will post to a controller function with the form data in $_POST variable. You validate the data in that function of the controller and do some DB inserts or updates. Then you show the success message as a view or in case of error a fail message.

See the form validation tutorial in CodeIgniter's user guide here.


I'd go with the model so your validation can be reused. Models should handle the data and the controller should direct it to where it needs to go.


The code that make the validation must be in the model, but the call to this code must be in the controller.

Something like this:

class MyAwesomeUserModel {
   public function isValid()
   {
       //some code to validate the user
   }
}

class MyUserController {
   public function myUserAction()
   {
      //some code to insert the input of the user in the model
      if($userModel->isValid()){
         //do nice things with the data and send some message/data to the view
      } else {
         //send 'nice' error messages to the view
      }
   }
}

This is just the way I use, may not be the best way, but it's the best fit in my application. And that's what matters, you should look for what best suits your application.

0

精彩评论

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