Can View talk directly to Model?

Asked

Viewed 464 times

2

In MVC a View serves to handle the entire user interface, the Model serves to contain the classes that represent the system and its business rules and the Controller performs the communication between the View and the Model (something like controlling the data flow), following this line of reasoning I can conclude that both the View and the Model do not talk to each other.

Follow a short example in Java to contextualize:

Viewpessoacadastro class:

public class ViewPessoaCadastro extends JFrame {            
    public ViewPessoaCadastro() {
        initComponents();
    }
    
    private void Salvar(ActionEvent evt) {//Clique
        //Salvar os dados.            
    }                       

    private void Listar(ActionEvent evt) {//Clique                        
        //Obtem todas as pessoas cadastradas e exibi para o usuario.
    }                           
}

Class Controllerpessoa:

public class ControllerPessoa {
    Pessoa pessoa;
    
    public ControllerPessoa(Pessoa pessoa) { 
        this.pessoa = pessoa;
    }
    
    public void salvar() { 
        pessoa.salvar();
    }
    
    public void alterar() { 
        pessoa.alterar();
    }
    
    public List<Pessoa> listarTodas() { 
        List<Pessoa> pessoas = pessoa.listarTodas();
        return pessoas;
    }
    
    public List<String> obterErrosValidacao() { 
        List<String> errosValidacao = pessoa.validar();
        return errosValidacao;
    }
}

Classe Pessoa:

public class Pessoa {      
    private String nome;
    private int idade;

    public Pessoa() { }

    public Pessoa(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }
    
    public void salvar() { 
        //Rotina para salvar no banco de dados.
    }
    
    public void alterar() { 
        //Rotina para registrar a alteração dos dados no banco de dados.
    }
    public List<Pessoa> listarTodas() {
        //Rotina para listar todas as pessoas salvar no banco de dados.
        ...            
    }
    
    public List<String> validar() { 
        //Rotina para validar a classe pessoa (Regras de negocio).
        ...
    }
    
    /*Getters e Setters*/
    public String getNome() { return nome; }

    public void setNome(String nome) { this.nome = nome; }

    public int getIdade() { return idade; }

    public void setIdade(int idade) { this.idade = idade; }
}

Doubts

Considering the above example in Java I came up with the following question:

Where I fill the class attributes Pessoa, I do this in the view by creating a type object Pessoa and then pass it on to the class builder ControllerPessoa or I create a method in class ControllerPessoa containing all parameters representing class attributes Pessoa? Considering the above question there is some possibility of View talking directly with Model?

PS:They can give examples in other languages too, but preferably could be Java itself.

  • is usually a function of helpers make this view communication with model.

  • @Danielomine the helpers are a fourth layer?

  • What technology are we talking about? I know it’s in Java, but what framework MVC?

  • Dener, yes, is a "Presentation layer". Do not confuse with "service layer".

  • @Ciganomorrisonmendez no technology, if you want you can cite some MVC framework :)

  • @Danielomine did not know that there were other layers besides the three main.

  • MVC is something more generic. There are several variations such as MVVM, PM, MVP, etc. For beginners, there is no need to go so deep as it will only complicate understanding. You will know what standard to adopt when needs arise.

  • @Danielomine can MVC be used without these other patterns? If yes, this is how I can collect information from the view and send it to the model so that the information is persisted in some database?

  • For now, forget these other patterns from the previous comment. On the view take something from the database, use Gof (Observer standard). See reply from Andrew

Show 4 more comments

1 answer

2


In the definition of Gof (Gang of Four), the only communication allowed between Model and View is using the Design Pattern Observer. No problem at all view "chat" with a model as long as this "conversation" is in standard format Observer, namely, the view can only observe the changes of model to reflect this for the user. In this case and only in this case, the controller is not involved and the model and view can communicate. Otherwise, the controller shall be invoked for communication between view and model.

What is common to use to assist in this communication is the standard Viewhelper located between the controller and the view. This standard aims to get the data from view and convert them to a pre-formatted object to be sent to the controller. The controller in turn, may have an association with model and it is he who carries out the action of recovering the data from view and persist the data in model.

In short, it is not appropriate to view have any association with model, except in a single case that is when the view notes changes in model to reflect this for the user. This is done using the standard Observer. Finally, to help the controller to carry out this communication, the standard is commonly used Viewhelper.

Update

You can interpret this definition and apply it according to your understanding. The important thing is to follow the principles of MVC Design Pattern.

Let me give you an example: Imagine that you are developing in a web environment, where you can consider an HTML form like the View layer, the Servlet that intercepts requests like the Controller layer and domain classes like the Model layer. A very simple code would look something like this:

VIEW

<form method="post" action="cadastrar">
<input type="text" name="nome" placeholder="Nome da pessoa"/>
<input type="text" name="idade" placeholder="Idade da pessoa"/>
<input type="text" name="frase" placeholder="Frase predileta"/>
<button type="submit">Enviar</button>
</form>

A simple form that will send a Person’s name, age and favorite phrase to a mapping "register".

VIEWHELPER

public class PessoaViewHelper implements IViewHelper{
   public Entidade getView(HttpServletRequest request) {
      Pessoa p = new Pessoa();
      p.setNome(request.getParameter("nome");
      p.setIdade(request.getParameter("idade");
      p.setFrasePredileta(request.getParameter("frase");
      return p;
   }
}

In this case, class Pessoa inherits Entidade. Soon, your Viewhelper is extracting the data from request coming from the browser and transforming into an object that is recognizable by the controller.

CONTROLLER

public class MyServlet extends HttpServlet {
   IViewHelper viewHelper;
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        viewHelper = new PessoaViewHelper();
        Pessoa pessoa = viewHelper.getView(req);

        //Nesse momento, seu objeto pessoa contém os dados da view extraídas pelo view helper
       //Aqui você executa sua lógica para fazer o que quiser com o model pessoa.
       //...
       resp.getWriter().write("Pessoa cadastrada...bla bla bla");
    }
}

Controller does not need to execute view extraction logic or execute validations, precisely because now it has an auxiliary, which is viewhelper.

This was a very simplified example of how data extraction logic would work using the viewhelper.

I hope I’ve helped.

  • The Viewhelper and a fourth layer?

  • You might consider it. But actually it’s an auxiliary layer that sits between the view itself and the controller. It is the viewhelper that extracts the data from the view and passes to the formatted controller in a way that the controller can understand and manipulate the correct model.

  • You can show in a small example how Viewhelper extracts the data from the View and passes to the Controller?

  • Yes, I will do the example here and edit the answer. Just a moment.

Browser other questions tagged

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