Validation of MVC forms - PHP

Asked

Viewed 1,052 times

2

To validate forms with the concepts of MVC, it would have to be in the Controller, Model, or View? Researching in internet I’ve seen some articles on the subject, but some recommend doing model others in the view, at the end, I can insert PHP codes into view? This method does not get the polluted code?

3 answers

2


It is recommended to use validation within the model, and how much to use php code in the view can, but only to render some data coming from the controller. Example, use foreach/variables/for etc to render data from the controller...

  • You have to use object orientation or I can recover this way? if(isset($_POST['btnExemple'])) {...} It’s just a basic question for a beginner like me :p

  • @Guilhermegouveiaalves not understood, MVC most is done in Object Orientation you use some framework?

  • I am not using Framework, me and a friend who is beginner we are also making a simple application for studies...

1

Validation in the view is only used to avoid an "invalid" request, but this validation should not be trusted since the user can change it.

The most reliable validation is done on the server, this question of doing it in the controller or model is very conceptual, goes from your organization/ methodology, in both cases will work.

By using Zend Framework 2, I created the custom of creating an object for form (which turns the form into html) and another object for filtering and validating the data, both objects are part of the Model layer, as they contain business rules, but are handled in the controller, I consider it a well organized way and recommend it.

Follow an example:

class ProdutosController
{
    /**
     * Este action insere produto no banco de dados
     */
    public function addAction()
    {
        $requisicao = $this->getRequisicao(); // requisição
        $dados      = $requisicao->getPost(); // dados enviados pelo form

        $entidade = $this->getEntidade; // entidade, mapeamento da tabela produtos do banco de dados
        $model    = $this->getModel(); // model, classe que conversa diretamente com o BD
        $form     = $this->getForm(); // Objeto form para montar formulário HTML

        // Se requisição for post, é porque usuário enviou o formulário
        // caso contrário é GET então ele está visualizando o form de inserção
        if ($requisicao->isPost()) {

            // Injeta objeto que filtra e valida os dados
            $form->setInputFilter($entidade->getInputFilter());

            // Joga os dados enviados pelo form HTML pra dentro do objeto form
            // assim será possível valida-los e outras ações que são feitas pelo objeto form
            $form->setDados($dados);

            // Verifica se o form foi validado com sucesso (executa validações do inputFilter)
            if ($form->isValid()) {

                // hidrata/popula a entidade com os dados que estavam no form
                $entidade->hidratar($form->getDados());

                // insere a entidade no banco de dados
                $model->insert($entidade);

                // Após inserção, redireciona para listagem
                $this->redirect()->toRoute('produtos/lista');
            }
        }

        // Caso requisição não seja POST ou caso validação do form tenha falhado
        // então carregar a view
        // caso validação do form tenha falhado, vai enviar as msgs de erro para a view tb

        // retornar um array é o jeito do Zend de enviar variáveis para a view
        return array(
            'variavel1' => 'valor1',
            'variavel2' => 'valor2',
            'variavel3' => 'valor3',
            'form'      => $form,
        );
    }
}
  • Would you have an example? I’m beginner with PHP and I have many doubts.

  • @Guilhermegouveiaalves I added an example with comments to facilitate, some things there are features of Zend Framework 2, others are concepts that you can use in any MVC application.

0

The validation in controller could not, because it only controls the requisition and the view just shows the look to the user with any output of data representation. And following the reasoning that validation is part of the "rule of business", then left to the model.

An alternative would be to create an additional directory outside of MVC only for calling form validation Inputfilter, Validator or as I usually do, Filter

example: 01

app/
|___ Model/
|
|___ View/
|
|___ Controller/
|
|___ Filter/

And also nothing prevents from creating the directory within the "model" itself pointing out that validation is part of the "business rule"

example: 02

app/
|___ Model/
|      |___ Filter/
|
|___ View/
|
|___ Controller/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.