Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validation in mvc php

I don't know which one is the best? do you think it's better to validate user login form or other forms in controller or it's better to define one class for example 'security class' in model to validation? or define some classes for validation? do you know a better choice or good technique?

<?php
class acontroller{
.
.
.
private function loginformAction()
{
    $this->actionform='loginform';
    $this->errorMsg=array();
    if(isset($post)){
        if(empty($post('aliasName'))){
                       ...
        }else{
           ...
                    }
        if(empty($post('password'))){
                      ...
        }
        if(empty($post('re_password'))){
                      ...   
        }
        if(!empty($post('password')) && isset($post('re_password')) ){
                      ...
        }
    }

    $this->render();
}
  .
  .
  .
 }   
like image 787
navid Avatar asked Nov 30 '12 18:11

navid


Video Answer


2 Answers

Validation is part of the domain logic. Controller should have nothing to do with this. It only has to pass the incoming request values to the proper parts of model layer.

The validation itself should happen in domain objects within the model layer. Also, in some forms you have to worry about data integrity (i.e. unique usernames in registration form). In that case the data integrity checks actually should be handled by data mappers by, essentially, passing data to SQL database, which performs the check and, if there is a violation, it triggers an exception on DB abstraction.

Update

Since your problems is dealing with authentication/authorization, you might find this post relevant.

like image 54
tereško Avatar answered Sep 29 '22 03:09

tereško


IMO 'Form Validation' aka "is field X filled in? check length, check content, etc" can be handled in the Controller, but 'User Authentication/Access Control' is best handled as its own Model object.

In practice I have a 'Form' Model object that both builds and validates forms so I'm not re-implementing the code in every controller that takes input.

like image 39
Sammitch Avatar answered Sep 29 '22 01:09

Sammitch