Chris Tonkinson
Chris Tonkinson

Reputation: 14459

MVC paradigm: exposing model and controller from view

I find myself needing to have a View expose its Model and Controller references. Is this the smell of bad design? Or is this considered "safe" practice?

For example: I have a list (composed of a ListView, ListController, and ListModel) and many list items (composed of a ItemView, ItemController, and ItemModel).

When I create the ItemModel, ItemView, and ItemController for each list item, I pass the ItemView instance off to the ListView. But, at some later point, my ListController needs a reference to the corresponding ItemController instance.

So, would it be more proper to pass both the ItemView and the ItemController in to ListView::addItem(), or just pass in ItemView and expose an instance method such as ItemView::getController()?

Or doesn't it matter? Is each approach equally viable? If followed to their logical conclusion, does either tactic result in an anti-pattern?

Upvotes: 0

Views: 207

Answers (3)

Robert Harvey
Robert Harvey

Reputation: 180787

But, at some later point, my ListController needs a reference to the corresponding ItemController instance

Why? If you're decoupling your classes properly, you shouldn't need this.

Controllers almost always address a functional domain. An example of such a domain might be "Sales" or "Admin." In addition, MVC also supports the use of "Areas," which provides an additional hierarchical level of organization.

Adding references to controllers from other controllers is at cross-purposes with this organizational structure. If you need to combine functionality to make your code more DRY, ordinary refactoring will accomplish that. You can also inherit controllers from a base class containing common functionality.

Upvotes: 1

Mattias Åslund
Mattias Åslund

Reputation: 3907

In the mvc pattern the users request shall be routed to a controller, say invoicecontroller, that has actions. Lets say the default action, Index, returns a list of invoices; the controller then creates a model with a list of invoice objects, instantiates the correct view and injects the model into the view. Now it is the views turn to do its magic. It renders the best view it can with the data it has, which may include routes to one or more controllers. In NO instance should the view (or model) do business logic themselves. That said, I totally agree with Jakub. Hope that helps.

Upvotes: 1

Marcel Valdez Orozco
Marcel Valdez Orozco

Reputation: 3015

Considering you are not actually showing any code at all. In my opinion, you should change your design. A controller is not supposed to communicate with another controller (directly), MVC dictates it: reference.

If you need to invoke a controller action from another controller, consider using delegates or composition. Instead of directly invoking the controller action.

Upvotes: 0

Related Questions