Question

I'm separating my code similar to MVC (models, views, and controllers).

Let's say I have two view classes, one is conceptually a page (contains many items) and another is just a widget (like a list of recent news).

Here are the ways I see of doing it:

  1. The controller instantiates both the page and widget classes, then passes the widget object into the page. If the page has a lot of widgets, I'd have to figure out how to pass it all in without it being confusing.

    class PageController {
        function foo() {
            Widget widget1 = new Widget();
            Widget widget2 = new Widget();
            Page page = new Page(widget1, widget2);
        }
    }
    
    class Page {
        function Page(Widget widget1, Widget widget2) {
            //do something with the widgets
        }
    }
    
  2. The page instantiates the widget class. But now the page class has references to all sorts of views instead of being able to place the view where ever as long as it has the appropriate interface.

    class PageController {
        function foo() {
            Page page = new Page();
        }
    }
    
    class Page {
        function Page() {
            Widget widget1 = new Widget();
            Widget widget2 = new Widget();
            //do something with the widgets
        }
    }
    
  3. Something else?

What is your advice and why?

Thank you.

Was it helpful?

Solution

I actually side with approach 1 in some ways. I would say Page should be able to be instantiated with or without widgets. You can add a collection of widgets to begin with and/or one at a time through some other provision within the Page as you run through your business logic and rules.

This gives you more flexibility to modify the construction of page as you go.

Widgets contain information on how they function and their presentation within the layout of the page.

Page should only be responsible for getting the information/instructions from the contained widgets and initialize/render them. This will allow for a more flexible and fluid design.

OTHER TIPS

Conceptually, #2 makes the most sense to me.

It's perfectly fine to have coupling between views if one type of view contains another. For example, it should be the page's job to manage where to place each widget, when to hide certain widgets etc.

However, the page shouldn't care about events pertaining to those widgets unless it needs to. If a widget has a button, it should just callback to a controller and skip telling the page... unless it causes the widget to be resized and the page needs to lay things out differently.

Hopefully this is useful to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top