validation in mvc php

2020-02-29 02:20发布

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();
}
  .
  .
  .
 }   

2条回答
贪生不怕死
2楼-- · 2020-02-29 02:52

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.

查看更多
来,给爷笑一个
3楼-- · 2020-02-29 02:53

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.

查看更多
登录 后发表回答