views:

342

answers:

6

NOTE: This question has been updated to provide more detail and insight than the previously.

UPDATE: I just want to say thank you to everyone who responded. I'm still pretty much in the dark on what design pattern would work best for the Widget. Perhaps one of the Factory or Builder patterns?


I am just getting started on a new project and need to use MVC, OO and design patterns.

Here's the idea: Imagine a page that displays a set of widgets. These widgets are (usually) charts that are based off of data contained in several separate tables in the database. I use a running example of page that reports on a student's performance.

High Level Requirements

  • a page that displays a set of (HTML only) widgets.
  • widget's data will be based off a database query.
  • the page can be used to view separate datasets containing similarly laid out data. For example, a single page will display widgets that report on various aspects of a single student's performance.
  • want to see another student's performance, pull up another page. Displaying different widgets for different students is not needed (though it may be nice to have later).
  • There may be many students, but data contained in the database is similarly laid out for all students.
  • the way a widget is displayed may be changed easily (say changing a widget from displaying as a pie chart to display as a bar chart).
  • widgets should be able to be created quickly.

Low Level Requirements

  • Currently data does not change so widgets will not need to automatically update themselves.
  • Widgets may represent a ratio of two things (eg. a ratio of failed tests to successful tests as a pie chart), a series of points, or sometimes a single numeric value.
  • Development of new widgets should be a breeze, existing code need not be modified.
  • Framework to be used: Zend Framework, based on MVC.

There are (minimally) three things to define a widget: the dataset to report on (in the example above, the student ID), the query that describes the metric being reported, and a render mode (barchart, timeseries etc).

Here is a pass at breaking down the responsibilities of each layer of the MVC:

View: Zend views are HTML templates with PHP injected. They will contain one of several types of widgets. Widgets are of various forms including: static JPEG images (loaded from a remote site ie: <img src="http://widgetssite.com?x=2&amp;y=3"/&gt;, JSON based javascript widgets, or charts of various kinds (piechart, bar chart etc.)

Controller: Creates the widgets, assigns them to the view afterwards. The set of widgets that is to be displayed on a page needs to be maintained somewhere. Since I can't think of a good way to do this in the view, I'll add this to the controllers responsibilities for now. If there's a better place for this please shout. The controller will also have to handle any other input parameters and passing them to the widget. For example, the data_set id which may be passed at the url line as http:/.../report/?student_id=42

Model: The model, in the Zend Framework, is responsible for pulling the data and as such will most likely contain a class for each widget for accessing the database.

Some points:

  1. The model here, represents the data for a particular widget. So necessarily, it will need to know what the query is going to be, in order to pull together the tables necessary to fetch that data.

  2. There's an additional processing step that will most likely be necessary before the widget can present the data. This is dependant upon which renderer will be used. Sometimes it may require forming a url out of the data returned. Other times, a JSON array. Other times perhaps creating some markup. This can go either in the model or the controller or the view. Unless anyone can think of a good reason to move it to the controller or view, it is probably best to let this live in the model and keep the view and controller thin.

  3. Likewise, a widget will be made up of 3 things, its parameters, its data, and its renderer.

    One big part of the question is: What's a good way to represent the widget in an Object Oriented design? I already asked this once, couldn't get an answer. Is there a design pattern that can be applied to the Widgets that makes the most sense for this project?

    Here's a first pass at a rather simple class for the Widget:

    class Widget{ 
      //method called by the view 
      render() {//output the markup based on the widget Type and interleaved the processed data} 
    
    
      //methods called by the controller: 
      public function __construct() {//recieve arguments for widget type (query and renderer), call create()}  
      public function create() {//tell the widget to build the query, execute it, and filter the data} 
      public function process_data() {//transform into JSON, an html entity etc} 
    
    
      //methods called by the model: 
      public function build_query() {...}; 
      public function execute_query() {...}; 
      public function filter_data() {...}; 
    } 
    

    Looking at it, I can already see some problems.

  4. For example, it is straightforward to pass the widget that was created in the controller to the View to render.

    But when it comes to implementing the model it seems not so straight forward. Table Gateway Pattern is simpler to implement than ORM. But since table gateway pattern has one class for each model/table it doesn't seem to fit the bill. I could create a model for a particular table, and then within that, instantiate any other models needed. But that doesn't seem so to fit the Table Gateway Pattern, but rather ORM pattern. Can Table Gateway Pattern be implemented with multiple tables? What alternatives are there? Does it make sense that the controller creates the widget and the widget creates the Model?

  5. Another issue that arises is that this design does not enable ease of widget creation. ie. Say I wanted to create a PiechartWidget, how much code can be reused? Would it not make more sense to use some OO ideas such as an interface or abstract classes/methods and inheritance?

    Let's say I abstract the Widget class so only the shared methods are defined concretely, and the rest are declared as abstract methods. Revising the Widget class to make it abstract (second pass):

    abstract class Widget{
    
    
      private $_type;
      private $_renderer;
    
    
      //methods called by the controller:
      //receive arguments for widget type (query and renderer), 
      protected function __construct($type, $renderer) {
        $this->_type = $type;
        $this->_render = $renderer;
        $this->create();
       } 
    
    
      //tell the widget to build the query, execute it, and filter the data
      private function create() {
        $this->build_query();
        $this->execute_query();
        $this->filter_data();
      }
    
    
      //methods called by the model:
      abstract protected function build_query();
    
    
      protected function execute_query() {
        //common method
      }
    
    
      abstract protected function filter_data();
    
    
      //method called by controller to tranform data for view
      //transform into JSON, an html entity etc
      abstract protected function process_data();
    
    
      //method called by the view
      //output the markup based on the widget Type and interleave the processed data
      abstract protected function render(); 
    }
    

    Is this a good design? How could it be improved?

  6. I assume writing a new widget will require at least some new code to build the query, and maybe filter the data, but it should be able to use preexisting code for almost all of the rest of its functionality, including the renderers that already exist.

I am hoping anyone could provide at least some feedback on this design. Validate it? Tear it apart. Call me an idiot. That's fine too. I could use any forward traction.

A few specific questions:

Q1. What's the best way to implement the renderers, as part of the Widget class or as a separate class? 1a. If separate, how would it interact with the widget class(es)?

Q2. How could I improve this design to simplify creation of new kinds of widgets?

Q3. And lastly, I feel like I am missing something here with regards to data encapsulation. How does data encapsulation relate to the requirements and play out in this scenario?

+1  A: 

You may consider using Subject Observer Pattern

Have your class, named DataReader as single Subject. Your multiple widgets will act as Observers. Once your DataReader receives data from server, it (Subject) will inform multiple widgets (Observer).

Your individual widgets may have different presentation to present to same set of data from DataReader.

Update

In the message where subject notify observer, you may include the message type information as well. Widgets will only process message type, which is within their own interest, and ignore rest of the message.

Yan Cheng CHEOK
Thanks for your answer. I'm curious if it applies in the case that widgets may be based off of separate queries.Also, with respect to the second part of my question, how best to integrate it into an MVC design?
hinghoo
See my update ;)
Yan Cheng CHEOK
+3  A: 

For #2, if you are using WPF on windows, or Silverlight in general, consider using MVVM pattern (Model-View-ViewModel), here is explanation with a WPF implementation: MVVM at msdn

For #1 (comments not answer): For exact implementations (and minor variations) of MVC, it really depends on what language you are using.

Another alternative to MVC is MVP Model View Presenter

Remember the goal of OO is not to cram design patterns into your code, but to create maintainable code with less bugs/increased readability.

Chris O
+1  A: 

It sounds like you want to use MVC and other patterns because they are the new buzz words. Splitting your design among model view and controller should tell you how to spread the functionality of your application. Although I totally agree that using MVC is the correct approach, I suggest you research the pattern and look at some source code that implements it. As a start to your question though, the widgets that will be displayed will be your views, that much should be obvious. Input from the user, such as changing a parameter of some widget or requesting other information will come into your application and should be handled by a controller. A concrete example of this is a Java-based HttpServlet. The controller servlet receives the user request and asks the lower layers of your app (Service, Persistence, etc) for an updated representation of your model. The model includes all of your domain-specific objects (i.e the data from your databases, etc). This data (the updated model) comes back to the controller, which in turn pushes out a new view for the user. Hopefully that is enough to get you started about designing your app.

As further help, you could consider using a framework to assist in the development of your app. I like Spring a lot, and it has a first class MVC implementation that really helps guide you to designing a correct MVC web app.

darren
feel free to comment for the down vote people
darren
+1  A: 

The purpose behind all of these ideas -- MVC, patterns, etc. -- is essentially the same: every class should do one thing, and every distinct responsibility in your application should be separated into distinct layers. Your views (page and widgets) should be thin and make few if any decisions other than to present data gathered from the models. The models should operate on a data layer agnostically, which is to say they should not know whether the source of their data is a specific kind of data source. The controllers should be thin as well, acting basically as a routing layer between the views and models. Controllers take input from the users and perform the relevant actions on the models. The application of this concept varies depending on your target environment -- web, rich client, etc.

The architecture of the model alone is no trivial problem. You have many patterns to choose from and many frameworks, and choosing the right one -- pattern or framework -- will depend entirely on the particulars of your domain, which we have far too few of here to give you more specific advice. Suffice it to say it is recommended you spend some time getting to know a few Object-Relational Mapping frameworks for your particular technology stack (be it Java, .NET, etc.) and the respective patterns they were built on.

Also make yourself familiar with the difference between MVP and MVC -- Martin Fowler's work is essential here.

As for design patterns, the application of most of the standard GOF patterns could easily come into play in some form or another, and it is recommended you spend time in Design Patterns or one of the many introductory texts on the subject. No one here can give specific answers as to how MVC applies to your domain -- that can only be answered by experienced engineers in cooperation with a Product Owner who has the authority to make workflow and UI decisions that will greatly affect such decisions in their particulars.

In short, the very nature of your question suggests you are in need of an experienced OOP architect or senior developer who has done this before. Alternatively give yourself a good deal of time in intensive study before moving forward. The scope of your project encompasses a vast amount of learning that many coders take years to fully grasp. This is not to say your project is doomed -- in fact you may be able to accomplish quite a lot if you choose the right technology stack, framework, etc., and assuming you are reasonably bright and focused on the task at hand. But getting concepts as broad as "MVC" or "OO" right is not something I think can be done on a first try and under time constraints.

EDIT: I just caught your edit re: Zend. Having a framework in place is good, that takes care of a lot of architectural decisions. I'm not familiar with Zend, but I would stick to its defaults. Much more depends here on your ultimate UI delivery -- are you in a RIA environment like Flash or Silverlight, or are you in a strict HTML/JavaScript environment? In either case the controllers should still be thin and operate as routers taking user requests from HTTP gets and posts, and immediately handing off to the models. The views should remain thin as well and make as few decisions as possible. The concept of MVC applied in a web environment has been pretty well established by Rails and the frameworks that followed, and I'm assuming Zend is similar to something like CakePHP in this regard: the application server has a routing system that maps HTTP calls to controller actions that respond with specific views. The request/response cycle is basically this:

  1. User request posted through a URL
  2. Router hands control to a controller class
  3. Controller makes a call to a model with the given params
  4. The model operates on the data, posts back to the controller
  5. The framework maps the finished data into a view, with some kind of code-behind that puts the results of the request in the view's scope.
  6. The framework creates html (or xml or whatever) and posts back to the caller.
Dave Sims
The ultimate UI delivery == a strict HTML/JavaScript environment.
hinghoo
+2  A: 

High Requirements - a page that displays a set of widgets. widgets are based off of data contained in several separate tables in the database. - widget's data will be based off a database query. widget display its data in a particular way. - widgets should be able to be created quickly.

Low Level Requirements - Data changes, multiple charts need to change, push model (from data to ui) - Development of new widgets should be a breeze, existing code need not be modified

Advice from design patterns basics - MVC supports one to many notification pattern, so yes, once your widget is initialized, created and connected to the web page, it should wait for notifications from the database. - Strategy pattern, your entire code should develop to a interface. New widgets should be added to a parametrized LinkedList (or some other data structure). That way new widget developers just implement the interface and your framework picks up these notifications without change to existing code.

Siddharth

Siddharth
I like your breakdown of the requirements. I apologize for not being clearer. One requirement was critically off, it's not a push type model. Widgets don't need to update _that_ frequently. Let me know if you have a suggestion for what pattern to use for the widget based on that.
hinghoo
A: 

NOTE: This is my new answer based on new the updated question.

Here is a proposed class diagram. I'm going to work on a sequence diagram. alt text

My old answer is here:

Based on the requirements you describe, your model is your database or data warehouse and your views are your pie charts, bar graphs, etc. I don't see the need for a controller, because it sounds like you have a one page dashboard with widgets.
You need to spend your time on the database model. Since you're doing all selects and no updates, go for a de-normalized data model that makes these queries efficient. You should put the results of these queries in a table type object (e.g. 2-dimensional array) or 3-dimensional array based on the amount of dimensions. You are limited to 3 dimensions unless you use animation.

LWoodyiii
Good advice on de-normalized schema for select-only systems! Please clarify what you mean by the last part "You should push...". Is that for caching? Or for the final representation?
hinghoo
LWoodyiii: Thanks, what you use to create that diagram?
hinghoo