Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - do I need to use Controller in the View?

As I know in the standard implementation of the MVC we pass Controller and Model to the View

But Im a little bit disagree with this idea. I dont want my view to know about both controller and model (oh no. maybe sometimes view needs model, but I'm sure that he can live without knowledge of controller)

In my opinion Controller should manage View and Model, and Model doesn't need to know about controller and view; view doesnt need to know controller (I dont exclude model because some implementations of views need to know about model to listen to changes in the model). So my idea is that view doesnt need to know about controller.

1. Here is one example:

public class MyView implements ButtonClickListener {

    private Controller myController;
    private Button myButton;

    // I commented out the model because we dont need it now 
    // we are talking about using controller in the view

    public MyView(Controller c/*, Model m*/) {
        myController  = c;
        myButton      = new Button(); // lets say that it is "register" button
        myButton.setOnButtonClickListener(this);
    }

    public void setRegisterButtonText(String text) {
        myButton.setText(text);
    }

    @Override
    public void onClick() {
        myController.tellToModelToDoSomething();
    }

}

And Controller:

public MyController implements Controller {

     private Model model;
     private View view;

     public MyController(Model model) {

          this.model = model;
          this.view  = new MyView(this);

     }

     public void tellToModelToDoSomething() {
          model.doSomeActions();
     }


}

2. And now how do I see this implementation without passing the controller:

My View:

public class MyView {

    private Button myButton;

    public MyView() {
        myButton = new Button();
    }

    public void setRegisterButtonText(String text) {
        myButton.setText(text);
    }

    public void setOnRegisterButtonClick(final Command command) {
        myButton.setOnButtonClickListener(new ButtonClickListener() {
                            @Override
                            public void onClick() {
                                command.execute();
                            }
                         });
    }

}

"Command" interface:

public interface Command {

     void execute(/*also can handle extra params*/);

}

And Controller:

public MyController implements Controller {

 private Model model;
 private View view;

 public MyController(Model model) {

      this.model = model;
      this.view  = new MyView();

      view.setOnRegisterButtonClick(command);

 }

 public void tellToModelToDoSomething() {
      model.doSomeActions();
 }

 private Command command = new Command() {

     public void execute() {
          tellToModelToDoSomething();
     }

 };

}

So why do I think that using controller in the view IS NOT GOOD:

We are mixing controller and view implementations, making new dependencies.

Also I think that View should contain only VIEWS and operations with them (and using controller and some of his methods already looks like logic).

In the first example view tells controller what to do. Are you agree? It looks like view controls the controller!

In the second example controller controls what to do and just says to the view what to do if some button (only view knows what button it will be) clicked

I always used the second scheme, but after reading a new one book about mvc, that says that we need to pass the controller to the view, I'm a little bit confusing.

Can you please help me to understand why am I wrong and show me some examples?

like image 393
pleerock Avatar asked Sep 17 '12 15:09

pleerock


People also ask

Should the view know the Controller in MVC?

The Model and View are independent of each other. Don't think of the Controller as the brains of the MVC structure. Think of it as the dispatcher which handles the requests from the browser, and dispatches them to the Model .

Does the Controller update the view?

The client only interacts with the view. The controller interacts with the view and indirectly with the client to update the model. The view does not directly cause modifications in the model, but all modification requests go through the controller.

Why do we need Controller in MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

How model view and controller interact with each other?

First, the browser sends a request to the Controller. Then, the Controller interacts with the Model to send and receive data. The Controller then interacts with the View to render the data. The View is only concerned about how to present the information and not the final presentation.


1 Answers

There is no MVC standard, as there are many implementations. Here's one interpretation of MVC that's taught in many textbooks:

The definition of the controller in this interpretation is that it handles events from the view, so the view must use the controller.

In standard MVC, the model contains and exposes data, the controller manipulates the model and accepts events from the view, and the view presents the model and generates events for the controller.

MVC is considered a transactional system, where a transaction is initiated by an event. The transactions typically look like this:

  1. An event (such as a button click) is generated on the view.
  2. The event information is passed from the view to the controller.
  3. The controller calls methods on the model to change it (setters and other manipulation methods which may update some database).

These first steps represent the V-C link and the M-C link. V-C exists because events are passed from view to controller to be processed instead of the view handling them directly. The M-C link exists because the model is updated by the controller according to the event that was fired.

From here, there are two paths. The first one:

  1. The transaction ends.
  2. Separately, the model fires its own events to indicate it has changed.
  3. The view is listening to the model and receives the event, and updates its model representation to reflect the changes.

This first path represents one interpretation of the M-V link. The M-V link is 1) the view getting information from the model for its data, and 2) the model telling the view to update since it has been modified.

The second path is only one step: once the controller has processed the event, the view updates immediately by simply refreshing all of its UI elements. This interpretation of the M-V link is that the model simply provides its information to the view, the same as point #1 from the M-V link in the first path above.

Here's some of your code modified for the MVC architecture I've described:

public class MyView implements View, ModelListener {

    private Button myButton;
    private Controller controller;

    public MyView(Controller controller, Model model) {
        myButton = new Button();
        myButton.setOnButtonClickListener(new ButtonClickListener() {
            @Override
            public void onClick() {
                controller.onRegisterButtonClick();
            }
        });
        this.controller = controller;
        model.addModelListener(this);
    }

    public void setRegisterButtonText(String text) {
        myButton.setText(text);
    }

    public void modelUpdated(Model model) {
        // Update view from model
    }
}

And the controller:

public MyController implements Controller {

    private Model model;
    private View view;

    public MyController(Model model) {
        this.model = model;
        this.view  = new MyView(this, model);
    }

    private void manipulateModel() {
        model.doSomeActions();
    }

    public void onRegisterButtonClick() {
        maniuplateModel();
    }
}

Then the model:

public class MyModel implements Model {
    private List<ModelListener> modelListeners = new ArrayList<ModelListener>();

    public void addModelListener(ModelListener ml) {
        if (!modelListeners.contains(ml)) {
            modelListeners.add(ml);
        }
    }

    public void removeModelListener(ModelListener ml) {
        modelListeners.remove(ml);
    }

    public void doSomeActions() {
        // Do something
        fireUpdate();
    }

    private void fireUpdate() {
        // Iterates backwards with indices in case listeners want to remove themselves
        for (int i = modelListeners.size() - 1; i >= 0; i-- {
            modelListener.modelUpdated(this);
        }
    }
}

ModelListener is pretty simple:

public interface ModelListener {
    void modelUpdated(Model model);
}

This is just one interpretation. If you want further decoupling between the different parts, you should look into the Presentation, Abstraction, Control (PAC) pattern. It's more decoupled than MVC, and is great for distributed systems as well. It's overkill for simple web, mobile, desktop applications, but some client/server applications and most cloud applications can benefit from this approach.

In PAC, you have three parts, presentation, abstraction, and control, but the abstraction and presentation (the model and the view) don't interact with each other. Instead, information passes only in and out of the control module. Furthermore, you can have multiple PAC sub-modules that interact with each other only through their controls, lending itself to a good pattern for distributed systems. Basically, the control module is the main hub of any data transfer.

Essentially, your interpretation of MVC may be different from mine or theirs. What matters is that you choose an architectural pattern and follow it to keep your code maintainable in the future. And you're right that there are ways to decouple MVC further. In fact, your example is a little bit like PAC, but instead of removing the V-C link, it removes the M-V link.

In any case, follow an architecture, document your architecture (so people know what your interpretation is), and don't stray from that.

like image 190
Brian Avatar answered Sep 19 '22 12:09

Brian