I am no stranger to software development having been a software engineer for over 25 years. I have developed in a variety of 2nd, 3rd and 4th generation languages on a mixture of mainframes, mini- and micro-computers (which are now called Personal Computers). I have worked with flat files, indexed files, hierarchical databases, network databases and relational databases. The user interfaces have included punched card, paper tape, teletype, block mode, CHUI, GUI and web. I have written code which has been procedural, model-driven, event-driven, component-based and object oriented. I have built software using the 1-tier, 2-tier and the 3-Tier architecture. I have created development infrastructures in 3 different languages. My latest achievement is to create an environment for building web applications using PHP that encompasses a mixture of 3-Tier architecture, OOP, and where all HTML output is generated using XML and XSL transformations. This is documented in A Development Infrastructure for PHP.

Before teaching myself PHP the only occasion where I came in contact with the concept of the model-view-controller design pattern was when I joined a team that was replacing a legacy system with a more up-to-date version that had web capabilities. I was recruited because of my experience with the language being used, but I quickly realised that their design was too clumsy and the time taken to develop individual components was far to long (would you believe two man-weeks for a SEARCH screen and a LIST screen?). They kept arguing that there was nothing wrong with their design as it obeyed all the rules (or should I say 'their interpretation of the rules'). I was not the only one who thought their implementation was grossly inefficient - the client did not like their projected timescales and costs so he cancelled the whole project. How's that for a vote of confidence for their design!

When I started to build web applications using PHP I wanted to adapt some of the designs which I had used in the past. Having successfully implemented the 3-Tier architecture in my previous language I wanted to attempt the same thing using PHP. My development infrastructure ended up with the following sets of components:

Data Access layer - a single component which contains all the DML (Data Manipulation Language) statements for a particular RDBMS engine. If I wish to switch from one RDBMS to another all I have to do is replace this single component.

Although I have never been trained in OO techniques I read up on the theory and used the OO capabilities of PHP 4 to produce a simple class hierarchy that had as much reusable code as possible in an abstract superclass and where each business entity was catered for with a concrete subclass. I published an article Using PHP Objects to access your Database Tables (Part 1) and (Part 2) which described what I had done, and I was immediately attacked by self-styled OO purists who described my approach as "totally wrong" and "unacceptable to REAL object-oriented programmers". I put the question to the PHP newsgroup and asked the opinion of the greater PHP community. This generated a huge response that seemed to be split between the "it is bad" and "it is good" camps, so I summarised all the criticisms, and my responses to those criticisms, in a follow-up article entitled What is/is not considered to be good OO programming.

I have absolutely no doubt that there will be some self-styled MVC purists out there in Internet land who will heavily criticise the contents of this document, but let me give you my response in advance:

I DO NOT CARE!

I have read the principles of MVC and built software which follows those principles, just as I read the principles of OOP and built software which followed those principles. The fact that my implementation is different from your implementation is totally irrelevant - it works therefore it cannot be wrong. I have seen implementations of several design patterns which were technical disasters, and I have seen other implementations (mostly my own) of the same design patterns which were technical successes. Following a set of principles will not guarantee success, it is how you implement those principles that separates the men from the boys. The principles of the various design patterns are high-level ideas which are language-independent, therefore they need to be translated into workable code for each individual language. This is where I have succeeded and others have failed. I have spent the last 25+ years designing and writing code which works, and I don't waste my time with ideas that don't work. Other people seem to think that following a set of rules with blind obedience is the prime consideration and have no idea about writing usable or even efficient code. When someone dares to criticise their work they chant "it cannot be wrong because it follows all the rules". The difference between successful and unsuccessful software is not in the underlying rules or principles, it is how those rules or principles are implemented that counts. Where implementation 'A' makes it is easier and quicker to develop components than implementation 'B', it does not mean that 'A' is right and 'B' is wrong, it just means that 'A' is better than 'B'. Where an implementation works it cannot be wrong - it can only be wrong when it does not work.

After researching various articles on the internet I came up with the following descriptions of the principles of the Model-View-Controller design pattern:

The MVC paradigm is a way of breaking an application, or even just a piece of an application's interface, into three parts: the model, the view, and the controller. MVC was originally developed to map the traditional input, processing, output roles into the GUI realm:

A model is an object representing data or even activity, e.g. a database table or even some plant-floor production-machine process.

The model manages the behavior and data of the application domain, responds to requests for information about its state and responds to instructions to change state.

The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.

The model is the piece that represents the state and low-level behavior of the component. It manages the state and conducts all transformations on that state. The model has no specific knowledge of either its controllers or its views. The view is the piece that manages the visual display of the state represented by the model. A model can have more than one view.

Note that the model may not necessarily have a persistent data store (database), but if it does it may access it through a separate Data Access Object (DAO).

The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application. Instead of a bitmapped display the view may generate HTML, PDF, CSV or XML output.

The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented.

The view is responsible for mapping graphics onto a device. A view typically has a one to one correspondence with a display surface and knows how to render to it. A view attaches to a model and renders its contents to the display surface.

A controller offers facilities to change the state of the model. The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate.

A controller is the means by which the user interacts with the application. A controller accepts input from the user and instructs the model and view to perform actions based on that input. In effect, the controller is responsible for mapping end-user action to application response.

The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application they appear as HTTP GET and POST requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.

The controller is the piece that manages user interaction with the model. It provides the mechanism by which changes are made to the state of the model.

Even though the above diagram is incredibly simple, there are some people who try to read more into it than is really there, and they attempt to enforce their interpretations as "rules" which define what is "proper" MVC. To put it as simply as possible the MVC pattern requires the following:

It must have a minimum of three components, each of which performs the responsibilities of either the Model, the View or the Controller, as identified above. You may include as many additional components as you like, such as a Data Access Object (DAO) to communicate with a relational database.

There is a flow of data between each of those components so that each may carry out its designated responsibilities on that data. What is not specified in MVC is how the mechanics of that flow are to be implemented. The data may be pushed by the Model into the View, it may be pulled by the View from the Model, or pulled into an intermediary (such as the Controller or an Observer) before it is pushed into the View. It does not matter how the data flows, just that it does flow. The actual mechanics are an implementation detail and can therefore be left to the implementor.

The MVC pattern does not identify from where each of these components is instantiated and called. Is there a mystical 4th component which oversees the 3 others, or can one of them oversee and direct the other two? As this is not directly specified in MVC the actual mechanics can be treated as a separate implementation detail.

Note the following:

HTML or PDF output can only be generated and output in one place - the View.

Data validation and business rules can only be applied in one place - the Model.

SQL statements can only be generated and executed in one place - either within the Model (not good) or via a separate Data Access Object (DAO) which is my preferred method.

There are some people who criticise my interpretation of the "rules" of MVC as it is different from theirs, and therefore wrong (such as how data moves from the Model to the View), but who is to say that their interpretation is the only one that should be allowed to exist? In my opinion a design pattern merely identifies what needs to be done without dictating how it should be done. Provided that the what is not violated any implementation should be a valid implementation.

I do not develop software which directly manipulates real-world objects, such as process control, robotics, avionics, or missile guidance systems, which means that a lot of the properties and methods which apply to real-world objects are completely irrelevant. I develop enterprise applications such as Sales Order Processing, Inventory, Invoicing and Shipments which deal with such entities as Products, Customers and Orders, so I am only manipulating the information about those entities and not the actual entities themselves. This information is held in a database in the form of tables, columns and relationships. Regardless of what properties or attributes a real-world object may have, in a database application it is only necessary to store those pieces of information that are actually required by that application. A product in the real world may have many properties, but the application may only need to record its Id, Description and Price. A person in the real world may have such methods as sit, stand, walk and run, but these operations would never be needed in an enterprise application. Regardless of the operations that can be performed on a real-world object, with a database table the only operations that can be performed are Create, Read, Update and Delete (CRUD). Following the process called data normalisation the information for an entity may need to be split across several tables, each with its own columns and relationships, and in these circumstances I would create a separate Model class for each table instead of having a single class for a collection of tables.

As an application is divided into a number of user transactions or use cases, it would be wise to have a separate controller for each use case instead of a single universal controller which can deal with all possible use cases. Some people advocate the creation of a separate controller for each use case, such as in GRASP - The Controller which states the following:

A use case controller should be used to deal with all system events of a use case, and may be used for more than one use case (for instance, for use cases Create User and Delete User, one can have a single UserController, instead of two separate use case controllers).

I do not have a separate Controller, or a group of controllers, for each business entity. Each user transaction (use case) does something with a database table, so I have placed the "something" into a reusable controller script, then use a component script to identify which table (model) should be the subject of that action. Because each business entity is a database table, and each database table has exactly the same operations, I have designed my controllers around the operations that can be performed on an unspecified database table where the name of that table is not known until run time. So instead of such controllers as Create User and Delete User, Create Product and Delete Product, Create Order and Delete Order I simply have Create Table and Delete Table. These controllers can be used with any table in any database, and because they have been reduced to this level of simplification they can be supplied as standard framework components and do not need to be created or modified by any developer. There is a separate controller for each of my Transaction Patterns.

In my implementation, as shown in Figure 2 and Figure 3, the whole application is broken down into a series of top-level components which are sometimes referred to as tasks, actions, functions, operations or transactions (that's user transactions, not database transactions), each of which is may be related to a Use Case. Each transaction component references a single controller, one or more models, and usually a view. Some components do not have a view as they are called from other components in order to perform a service, and once this service has been completed they return control to the calling component. Each component is self-executing in that it deals with both the HTTP GET and POST requests.

The Model is implemented as a series of business entity classes each of which contains all the properties and methods required by a single business entity. It is actually a subclass to an abstract superclass which contains properties and methods which are common to all database tables. The model is responsible for all data validation, business rules and task-specific behaviour, while the actual generation of DML (Data Manipulation Language) statements is performed in a separate DML class.

The DML class or Data Access Object (DAO) is the only object in the entire framework which is allowed to communicate with the database, and it can only be called by a model component. This isolates the model from the underlying database and allows the application to be switched from one RDBMS to another simply by switching to another DML class. Only the DML class deals with database resources - all communication with the entity subclass is by standard database-agnostic arrays.

The Controller is implemented as a series of controller scripts, one for each Transaction Pattern, which are activated by a component script. Unlike some implementations which require a separate controller for each transaction, each of my controllers is for a class (or type) of transaction, so the same controller script can be shared by all transactions of the same class. Each of these scripts deals with the following:

It handles the HTTP GET and POST requests.

It instantiates an object for each business entity identified by the component script.

It calls methods on those objects as appropriate. Most will perform some sort of communication with the database although some may not. Data is passed into and out of these objects as standard PHP arrays. In this way an object can deal with any number of database occurrences both as input or output.

It calls the relevant view object to create output in either HTML, PDF or CSV.

Controllers do not select which View to use. Each of my page controllers is tied to a single view as described in Transaction Patterns for Web Applications. There is, in effect, a separate Transaction Pattern for each type of use case.

The Model does not send updates to the View. When the Model has finished the actions requested by the Controller, the Controller will instantiate its one and only View, inject the Model(s) into the View, and the View will then extract all data from the Model(s) and render it in the desired format. There are separate Views for HTML, CSV and PDF output. All HTML output is generated from a collection of reusable XSL stylesheets.

The View does not send user gestures to the Controller. Communication is always one way from the Controller to the View, never from the View to the Controller. With web applications there are only two possible actions - GET and POST - and these are received by the Controller which then calls the appropriate method(s) on the Model(s) followed by a single call to the View.

The Model is never supposed to handle the output of its data to any particular device or medium. Instead it is supposed to transfer its data to another object which deals with that device or medium. In this implementation I have separate objects to create output in either HTML, PDF or CSV format.

Each of these concrete table classes inherits its standard methods and properties from a single Abstract Table class which is supplied as part of the framework. This ensures that all the common code is defined in one place but can be shared by many objects.

Each table class contains its own specific business rules and data validation rules, but all communication with the physical database is routed through a separate Data Access Object (DAO). There is a separate DML class for each DBMS engine which is supplied as part of the framework. This arrangement makes it possible to switch from one DBMS to another without having to make any changes to any table class. Currently supported DBMS engines are MySQL, PostgreSQL, Oracle and SQL Server.

The framework components are application-agnostic as they have no knowledge of the internals of any application component. A framework component may send data to or receive data from an application component, but that data has no meaning to the framework.

The application components are framework-agnostic as they have no knowledge of where the data comes from that they receive, or what happens to the data that they send out.

All default behaviour is provided by the framework components, so when a developer wishes to alter the default behaviour the only code that he/she has to write goes into one of the pre-prepared methods in a Model class. This also means that, as the author of the framework, I can alter or enhance the default behaviour of any component within the application simply by changing a framework component. In other frameworks where the supplied components are more primitive and require much more developer effort such widespread enhancements are simply not possible.

Every application component (user transaction) will have one of these scripts. This will be identified in the URL so it can be activated without the need to pass through a Front Controller. It is a very small script which does nothing but identify which model (business entity), view (screen structure file) and controller to use, as shown in the following example:

<?php
//*****************************************************************************
// This will allow a single occurrences of a database table to be updated.
// The identity of the selected occurrence is passed down from the previous screen.
//*****************************************************************************$table_id = "mnu_user"; // identifies the model$screen = 'mnu_user.detail.screen.inc'; // identifies the view
require 'std.update1.inc'; // activates the controller
?>

Where the controller requires access to more than one business entity, such as in a parent-child or one-to-many relationship in a LIST2 pattern, or a parent-child-grandchild relationship in a LIST3 pattern, then names such as $parent_id, $child_id, $outer_id or $inner_id are used.

The same screen structure file can used by components which access the same business entity but in different modes (insert, update, enquire, delete and search) as the XSL stylesheet is provided with a $mode parameter which enables it to determine whether fields should be read-only or amendable.

Note that no component script is allowed to access more than one view. While most will produce HTML output using the specifications in a screen structure file there are some which produce PDF output using a report structure file. Some components may have no view at all - they are called upon to take some particular action after which they return control to the calling component which refreshes its own view accordingly.

There is a separate pre-built controller script included in the framework for each of the patterns identified in Transaction Patterns for Web Applications. By simply changing the name of the controller script the whole character of the component will change.

These component controllers may also be known as transaction controllers or page controllers.

The controller does not know the names of the business entities with which it is dealing - these are passed down as variables from the component script. It will append the standard '.class.inc' to each table name to identify the class file, then instantiate a separate object for each table. Note that I did say "entities" in the plural and not "entity" in the singular. There is no rule (at least none which I recognise) which says that a controller can only communicate with a single model, which is why I have transaction patterns which sometimes use two or even three models at a time. Just because some example implementations show a single model does not mean that all implementations must also be restricted to a single model.

The method names that the controller uses to communicate with each table object are the generic names which are defined within the abstract table class. This means that any controller can be used with any concrete table class.

The controller does not know the names of any fields with which it is dealing - what comes out of the business entity is a simple associative array of 'name=value' pairs which is passed untouched to the View object which will transfer the entire array to an XML document so that it can be transformed into HTML.

In any INPUT or UPDATE components the entire contents of the POST array is passed to the business entity as-is instead of one field at a time. Again this means that no field names have to be hard-coded into any controller script, thus increasing their re-usability.

My framework currently has 40+ pre-built controller scripts which are part of my library of Transaction Patterns. The same pattern can be used with virtually any business object in the application, thus making them loosely coupled and highly reusable.

This is responsible for all communication the database by constructing queries using the standard SQL Data Manipulation Language (DML) using instructions passed down from the calling Business Entity class. There is a separate DML class for each different DBMS engine, such as MySQL, PostgreSQL, Oracle and SQL Server, which means that the entire application can be switched from one DBMS to another simply by changing a single entry in the configuration file. This means that it is also possible to develop an application using one DBMS engine but deploy it to use another.

Note that this class does not have any inbuilt knowledge of any database or database table, so a single class can be used to access any table in any database.

Each business entity is implemented as a separate class so that it can encapsulate all the properties and methods of that entity in a single object. As each of these business entities also exists as a database table a great deal of common code can be shared by inheriting from the abstract table class.

In its initial form a concrete table class requires very little information to differentiate it from another database table - just the database name, the table name, and the table structure. Rather than having to create each class file manually, as of June 2005 these can be generated for you as described in A Data Dictionary for PHP Applications. This provides the following facilities:

EXPORT - Make the details available to the application in the form of disk files which can be referenced by means of the include() function. Two files will be created for each database table:

<tablename>.class.inc - this is the initial class file for the database table. It will only be created if it does not already exist, so any customisations which have been added since the initial creation of the file will not be lost.

<tablename>.dict.inc - this contains the column details, key details and relationship details. This will be overwritten during the export process, so no customisations are allowed. All customisation should be performed in the dictionary and then exported to this file. Alternatively it is possible to make temporary customisations at runtime by placing code in the _cm_changeConfig method of the relevant table subclass.

The variables in the class constructor do not contain application data (that which passes through the object between the user and the database) but instead contain information about the application data. Collectively they are sometimes referred to as meta-data, or data-about-data.

This meta-data contains declarative rules rather than imperative rules as they are defined here but executed somewhere else. When the time comes (i.e. when the user presses a SUBMIT button on an HTML form) the user data passes from the Controller into the Model where it is passed to a validation object along with the meta-data, and it is the responsibility of the validation object to ensure that the user data conforms to those rules. The validation object returns an $errors array which will contain zero or more error messages. If there are any error messages then the operation is aborted.

The structure file is a simple PHP script which identifies the XSL stylesheet which is to be used and the application data which is to be displayed by that stylesheet. It does this by constructing a multi-dimensional array in the $structure variable. The following formats are available:

This identifies which XSL stylesheet to use. Note that the same stylesheet can be referenced in many different structure files.

tables

This associates the name of a zone within the XSL stylesheet with the name of some user data within the XML document. A stylesheet may contain several zones, and the XML document may contain data from several database tables, so it is important to identify which table data goes into which zone. Among the different zone names which you may see are main, inner, outer, middle and link.

zone columns

This allows you to specify attribute values for each table column in this zone.

The following keywords for column attributes are supported in the list/horizontal view:

Note that the 'align', 'valign' and 'class' attributes when added to a <COL> element in the HTML output are poorly supported in most browsers, so will be dealt with as follows:

The 'align' and 'valign' attributes will be converted to 'class' when written to the XML output.

The 'class' attribute will no longer be added to the <COL> element, but instead will be added to the <TD> element for every cell within the relevant column.

NOTE: if your screen structure file contains two or more of the 'align|valign|class' attributes for the same field then they will be combined automatically into a single 'class' value, so code such as:

This identifies which fields from the database table are to be displayed, and in which order. For a horizontal view (as in Figure 7) this identifies the columns going across the page. For a vertical view (see Figure 4) this identifies the rows going down the page. Note that each element within this array is indexed by a column number (horizontal view) or a row number (vertical view).

This behaviour can be overridden by adding 'display-empty' => 'y' to the item in the ['zone']['fields'] array in the screen structure file. This will cause every cell in that row to be output, even if it is empty.

When this information is written out to the XML document it will look something like the following:

colspan - will allow that field to span more than one column in the HTML table. Without it the remaining columns in that row would be blank.

rowspan - similar to colspan, but allows the field to extend vertically for more than 1 row.

cols - will override the value for multiline controls supplied in the $fieldspec array.

rows - will override the value for multiline controls supplied in the $fieldspec array.

align - specify horizontal alignment within this cell. See the HTML specification for details.

valign - specify vertical alignment within this cell. See the HTML specification for details.

size - will set the size of the textbox control for that field when data can be input or amended. This overrides the size value specified in the $fieldspec array. This option is available in both the detail/vertical and list/horizontal views.

display-empty - if the field is not present in the XML file then by default neither the label nor the field will be displayed. This option will cause the empty row to be displayed instead of being dropped.

label-only - this will cause a label to be printed on its own without an associated field value.

class - will allow that label or field to be enclosed in a class attribute, where the class name should be defined in the CSS file.

imagewidth - will override the value in the $fieldspec array when an image is displayed. This option is available in both the detail/vertical and list/horizontal views.

imageheight - will override the value in the $fieldspec array when an image is displayed. This option is available in both the detail/vertical and list/horizontal views.

The first two entries in row 3 use the rowspan option to extend down into row 4.

As the first two cells in row 4 are now occupied the entries for row 4 will now start from cell 3.

If there is the possibility that row 4 could be empty thus causing it to be dropped from the display, the 'display-empty' => 'y' entry will cause empty cells to be output instead. This avoids row 5 being moved up to take the position of the missing row 4, which is to the right of the first two cells and immediately below the last 2 cells in row 3.

The selectbox entry does not relate to any field from the database. It is a reserved word which causes a checkbox to be defined in that column with the label 'Select'.

The nosort entry (which can be specified in either of the columns and fields arrays) is optional and will prevent the column label from being displayed as a hyperlink which, when pressed, will cause the data to be sorted on that column.

In some cases it might be useful to display an empty column (no heading, no data), and this can be achieved by inserting a line in any of the following formats:

Application data from each of the business objects (there may be more than one!) which were specified in the component script. This data will appear in the data area of the HTML output. This area is broken down into one or more zones (e.g. 'main', or 'outer' and 'inner', or 'outer', 'middle' and 'inner'), and each object's data is allocated to one of those zones.

This is a standard process by which an XML document is transformed into HTML output using instructions contained within an XSL Stylesheet. This process is performed at the web server end by default, but it is also possible for it to be performed within the client browser, thus reducing the load on the server.

The framework contains a series of reusable XSL stylesheets each of which will present the data in one of the structures described in Transaction Patterns for Web Applications. These stylesheets are reusable because of one simple fact - none of them contain any hard-coded table or field names. Precise details of which elements from the XML file are to be displayed where are provided within the XML file itself from data obtained from a screen structure script which is placed into the <structure> element. This is a great improvement over my original software which required a separate version of a stylesheet for each component.

There are two basic structures for displaying data, and while some stylesheets use one or the other there are some which contain the same basic elements in different variations and combinations.

It is important to note that it is not a simple case of adding in extra columns to a row. An HTML table expects each row to have the same number of columns, so it is necessary to make adjustments on all other rows otherwise they will contain empty columns. Notice the following points about Figure 5:

'data1' has been told to span 3 columns, otherwise it would be no wider than 'data2a'.

Line 2 contains two labels and two fields. This dictates that each row must therefore contain 4 columns.

'data4b' does not have a label. This is allowed, but it is not possible to have a label without data.

'data4b' has been told to span 2 columns, otherwise it would be no wider than 'label2b'.

In an HTML table it is possible to have a single piece of data which spans more than one column, as shown in Figure 5. It is also possible to have a single piece of data which spans more than one row, as shown in Figure 6.

The same DETAIL view can be used by different components which access the same business entity in different modes (insert, update, enquire, delete and search) as the controller script will pass its particular mode to the XSL stylesheet during the transformation process. The XSL stylesheet will use the mode value to alter the way that it deals with individual fields by making them read-only or amendable as appropriate.

This is a LIST view which displays the contents of several database rows in horizontal rows going across the page. The top row contains column headings (labels) while the subsequent rows contain data, each row from a different database occurrence.

Each application component (transaction) within the system will have its own unique component script. Although this is not sharable, it is a very small script which does nothing but identify which Model, View and Controller to use, most of which are sharable. This arrangement allows me to achieve the following levels of reusability:

There is a separate Model class for each business entity (database table) within the application which encapsulates all the properties and methods necessary for that entity. This class can be shared by any number of components.

Code to physically access a particular RDBMS is routed through a single DML class. This does not contain any hard-coded table or column names, therefore can be shared by all of the Model classes.

Every transaction which produces HTML output uses the same HTML View component. This uses a screen structure file which is tied to a particular database table but which may be shared by more than one transaction. Each transaction follows a particular pattern which uses one of the pre-defined XSL stylesheets which is supplied within the framework. There are a dozen or so of these XSL stylesheets which can be used by any number of different transactions, and as they do not contain any hard-coded table or column names they can be used with any number of Model classes.

In my implementation I can add a new table to my database, import the details into my Data Dictionary, create the class file for the Model then create the initial transactions for the LIST1, SEARCH1, ADD1, ENQUIRE1, UPDATE1 and DELETE1 patterns, and be able to run them from my menu system, in under 5 minutes without having to write a single line of code. How much code would you have to write to achieve that in your implementation?

In your implementation how much code do you have to write for each Model in order to produce a working transaction? In mine it is none as the model classes are generated from my Data Dictionary and inherit a large amount of code from my abstract table class.

In your implementation how much code do you have to write to validate user input? In mine it is none as all user input is automatically validated using my standard validation object which compares each field's value with the field's specifications provided by the table structure file.

In your implementation how much code do you have to write for each View in order to produce a working transaction? In mine it is none as each HTML page is created from a pre-built View object which uses one of my pre-defined XSL stylesheets.

In your implementation how much code do you have to write for each Controller in order to produce a working transaction? In mine it is none as each transaction uses one of my pre-defined controller scripts.

In your implementation how many Controllers are tied to a particular Model and are therefore not sharable?. In mine I have 43 controllers which can operate on any Model, so they are infinitely sharable.

If your implementation cannot achieve the same levels of reusability/sharability as mine then please do not try to tell me that my implementation is inferior.

More information regarding the levels of reusability which I have achieved can be found in the following:

In this forum post someone asked advice on how the MVC pattern should be implemented, so I decided to offer some based on my experience of having successfully implemented the MVC pattern in a large web application. It seems that quite a few people took exception to my approach as it violated their personal interpretations of the rules of MVC.

Should the Model transmit its changes directly into the View, should the View extract the changes directly from the Model, or should the Controller extract from the Model and inject into the View? Actually, there is no hard and fast rule here, so any of these options would be perfectly valid.

MVC states that views access the model directly (ie not using the controller as a mediator) and that models should not know of controllers and views.

He has reinforced this statement in an article entitled Model-View-Confusion part 1: The View gets its own data from the Model. What he fails to realise is that different examples of MVC implementations show different ways in which the model obtains its data, so he cites the ones that follow his personal opinion as being "right" and dismisses all the others as being "wrong".

I feel that his interpretation of the statement "models should not know of controllers and views" goes too far. A model may have any of its methods called by another object, or may call a method on an object of unknown origin which has been injected into it, but it should not have any hard-coded dependencies on specific view objects or any methods which are tied to specific objects as this would introduce tight coupling between those objects. By using generic methods which can be used by multiple objects you are introducing loose coupling which makes the code more maintainable and less prone to error. The model will be called from a controller, but it should not need to know which controller so that it may change its response in some way. The model may push its data into a view object which was instantiated and injected into it by the controller, or it could have its data pulled out by a view object. In either case it should not need to know which view or controller requested that data, it should simply return the data and let the calling object do what it wants with it, which may be to render that data it whatever form is appropriate, which could be HTML, PDF, CSV or whatever.

In the MVC paradigm the user input, the modeling of the external world, and the visual feedback to the user are explicitly separated and handled by three types of object, each specialized for its task.

The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application.

The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate.

the model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller)

The formal separation of these three tasks is an important notion that is particularly suited to Smalltalk-80 where the basic behavior can be embodied in abstract objects: View, Controller, Model and Object. The MVC behavior is then inherited, added to, and modified as necessary to provide a flexible and powerful system.

Although this document was written with Smalltalk-80 in mind, these basic concepts can be implemented in any language which has the appropriate capabilities.

Notice that it concentrates on the responsibilities of the three components, and does nothing but "suggest" how the data may flow between them. Note the use of the term "usually" in the above list, and the phrase "commanding the model and/or the view to change as appropriate." Later in the same document you may find references to particular implementations, but as far as I am concerned these are suggested implementations by virtue of the fact that the words used are can, could and may. These are not imperatives such as must, should or will, and as such should not be regarded as required in any implementations.

In addition to dividing the application into three kinds of components, the MVC design defines the interactions between them.

A controller can send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document). It can also send commands to the model to update the model's state (e.g., editing a document).

A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. A passive implementation of MVC omits these notifications, because the application does not require them or the software platform does not support them.

A view requests from the model the information that it needs to generate an output representation.

So even in this definition there are several possibilities:

The controller can send commands to both the model and the view.

The model can send commands to both the view and the controller.

The view can receive commands from both the model and the controller.

Note that the word used is can and not should or must.

Which variation of these options you choose to implement is therefore down to your personal preferences or what options are available in your design.

So even though the MVC pattern does not (or should not, IMHO) dictate how the flow of data should be implemented, whether it should be pulled or pushed, or who should do the pulling or the pushing, TomB seems to think that the only implementations which are allowed are those which have received his personal seal of approval. Isn't this a little arrogant on his part?

I disagree (again). The Model contains whatever records it has been told to contain, either by issuing an sql SELECT statement, or by having data injected into it from the Controller. The View does not *request* any particular records from the Model, it deals with *all* records that are currently contained in the Model. Ordering and limiting are data variables which are passed from the Controller, through the Model and to the DAO so that they can be built into the sql SELECT statement. The View does *not* decide how to limit or sort the data - the data which it is given has already been sorted and limited.

Ordering, limiting and generally deciding which records to show is 100% display logic. By moving this to the model you've reduced reusability of the view.

I don't know about you, but if there are 1,000s of records to display, but the user wants to see them in pages of 10, it is much more efficient, both in time and memory, for the Model/DAO to use limit and offset values so that only the relevant records are actually read from the database. All of these records are then passed to the View, and the View displays every record which it has been given. It just does not sound practical to pass 1,000s of records to the View, then get the View to decide which 10 to display. Similarly it is far easier to sort the records by adding order by to the SQL query than it is to have code to sort them in the View.

This is no way reduces the reusability of the view as all HTML output is produced from a single pre-written View object which uses one of my pre-written XSL stylesheets. This single object can be used to create the HTML output for any transaction and any Model. What could be more reusable than that?

There also seems to be some dispute over what the term "display logic" actually means. A software application can be broken down into the following types of logic:

Display logic - code which generates the HTML output that is sent to the user. This exists in, and only in, the View.

Business logic - code which implements the business rules. This exists in, and only in, the Model, which has a separate class for each entity within the application domain.

Data Access logic - code which constructs and executes SQL queries to read or update data in a database. This exists in, and only in, the Data Access Object (DAO) which is accessed from the Model.

Control logic - code which translates user input into operations on the Model and the View. This exists in, and only in, the Controller.

It is clear to me that display logic is that code which directly generates the HTML output. The data which is transformed into HTML may come from any source, but the code which obtains or generates that data is not part of the display logic. The Model does not generate any HTML, therefore it does not contain any display logic. Similarly the Model does not generate and execute any SQL queries, therefore it does not contain any data access logic. This can be summed up as follows:

Code which transforms data into HTML is display logic.

Code which creates or obtains the data which is subsequently transformed into HTML is not display logic.

I'm sorry if my interpretation of these minor details is different to yours, but just because my interpretation is different does not mean that it is wrong. I still have components which carry out the responsibilities of Model, View and Controller, so as far as I am concerned my version of MVC is perfectly valid. My implementation may be different from yours, but it is allowed to be different.

According to some people there is supposed to be a rule which says that a Controller can only ever communicate with a single Model, but as I have never heard of this rule and have never been given any justification for its existence I see no reason to be bound by it. In my implementation each HTML page is broken down into a series of zones or areas, and each zone is populated using the contents of a different object as follows:

In all my previous programming languages I was able to populate different areas on the screen from different tables in the database, so I saw no reason why I should not do exactly the same with PHP. Each of my page controllers will deal with each of those applications objects independently and separately, regardless of the number, and not through any single composite object.

For example, take three database tables which are related as shown in Figure 9:

A typical screen will list multiple rows from the ORDER table in a single zone using the LIST1 pattern as shown in Figure 10. Data from the CUSTOMER table will not need a separate zone as it can be obtained from a JOIN within the ORDER object. Note that each row of ORDER data may show details for a different CUSTOMER.

A variation of this may show only those ORDERs for a single CUSTOMER using the LIST2 pattern, as shown in Figure 11. Here the CUSTOMER table has its own zone which displays one row at a time. This is separate from and in addition to the ORDER zone which can display multiple rows. Only those ORDERS which are related to the current CUSTOMER will be shown.

Another screen may only show those ITEMs for a single ORDER using the LIST2 pattern, as shown in Figure 12. Here the ORDER table has its own zone which displays one row at a time. This is separate from and in addition to the ITEM zone which can display multiple rows. Only those ITEMs which are related to the current ORDER will be shown. Any CUSTOMER data is obtained using a JOIN within the ORDER object.

Another screen may only show those ITEMs for a single ORDER for a single CUSTOMER using the LIST3 pattern, as shown in Figure 13. Here the CUSTOMER table has its own zone which displays one row at a time. This is separate from and in addition to the ORDER zone which can also only display one row at a time, and the ITEM zone which can display multiple rows. Only those ITEMs which are related to the current ORDER which are related to the current CUSTOMER will be shown.

The idea of forcing the page controller to go through a single composite object in order to deal with the separate database objects never occurred to me. Doing so would require extra effort which would achieve absolutely nothing (except to conform to a rule which I did not know existed) so as a follower of the KISS principle it is my choice, if not my duty, to avoid unnecessary complexity and stick with the simplest thing that could possibly work.

While not a direct criticism of my approach, a blog written by Fabien Potencier (who created the Symfony framework), contains the following statement:

I don't like MVC because that's not how the web works. Symfony2 is an HTTP framework; it is a Request/Response framework.

In my opinion anyone who says that the MVC design pattern is not suitable for the web has a blinkered mind which is being constrained by the circumstances in which that pattern was created and the way it was first implemented. It was originally designed for and implemented in a language which ran in a stateful environment on the desktop using a bitmapped display, and where it was possible for every keystroke to be detected by the program and to have an immediate effect on the output. Twenty plus years later the internet arrived with a totally different stateless protocol with its HTTP Request/Response cycle in which individual keystrokes are not detected - the client sends a request to the server, the sever processes that request and responds with a complete HTML document which causes the whole display to be rebuilt.

If you bother to look at the description of MVC its says nothing about being tied to software which runs in a stateful environment using a bitmapped display where every keystroke can be detected and processed. MVC is nothing more than a design which identifies three components which each have their own distinct and separate responsibilities. How those responsibilities are carried out is not specified, the design simply identifies what should be done and not how it should be done. MVC is not tied to a particular language, or a particular protocol, nor is it limited to a particular implementation. That blog also contains the following statement:

... because the MVC word is so overloaded and because nobody implements exactly the same MVC pattern anyway.

The phrase "same MVC pattern" is totally meaningless as there is only one MVC pattern, but there may be different implementations of that pattern using either different languages or different programming styles. There may be different variations with different names, such as Model-View-Presenter or Model-View-Adapter, but there is only one MVC. Provided that your software has three components which fulfil the responsibilities of the Model, View and Controller then you definitely have an implementation of MVC, and anyone who says otherwise is mistaken. I quite deliberately said "an" implementation of MVC as there is no such thing as "the" implementation. For example, with PHP applications the View component may use a templating system such as Smarty or one of the many other templating engines. Personally I prefer to use XSL. Some people put data validation in the Controller (which then results in a Fat Controller and a Thin Model), but I prefer to keep it in the Model with the other business logic. This means that all knowledge of any application is confined to the Model/Business layer while both the Presentation and Data Access layers are application-agnostic by virtue of the fact they do not contain any knowledge of any application. Controllers, Views and DAOs are supplied with the framework while individual Model classes are generated by the framework using table structures obtained from the application database which is designed and built by the developer.

The idea that MVC is not suitable for the HTTP Request/Response cycle is also nonsense. Take a look at Figure 14:

The Controller calls the appropriate method(s) on the Model(s) and waits for it/them to finish. Note that the results contain only data, no HTML.

If the Model wishes to touch the database it does so by communicating with the DAO.

The Controller calls the View with the result(s) from the Model(s) in order to transform the raw data into HTML.

The Controller sends the HTML response back to the client.

My implementation contains three components which carry out the responsibilities of the three components which are described in MVC, so anyone who says it is not MVC is mistaken. It also runs on the web, so anyone who says that MVC is not suitable for the web is mistaken.

My critics take great delight in telling me that my implementation is wrong because it breaks so many of their precious principles, especially SOLID. What they fail to realise is that I am only breaking their interpretation of these principles, and as I consider their interpretation to be seriously flawed I prefer to follow a more moderate and pragmatic interpretation which allows me to implement a practical solution which has as few unpleasant side effects as possible. Following rules which create problems instead of solutions is not my idea of good programming.

A Model which is responsible for more than one database table

Some people seem to think that it is perfectly acceptable to create a Model which deals with more than one database table, but I do not. In my view it breaks the Single Responsibility Principle, and my philosophy of one-class-for-each-database-table brings nothing but benefits and zero disadvantages. Instead of having to hand-craft each Model class and its associated methods I have a function which creates those classes using information obtained from the database schema. As the operations which can be performed on a database table are restricted to Create, Read, Update and Delete (CRUD) all the standard code for dealing with these operations is defined within a single abstract class which is inherited by every concrete table class.

A Controller which is responsible for more than one User Transaction

A user transaction (which may or may not include a database transaction) is a distinct unit of work (also known as "Use Case") which may be selected by the user from an option on a screen, either from a menu button or a navigation button. Figure 15 below shows a basic family of forms which perform the basic maintenance tasks on a database table.

Each of these tasks is a separate user transaction with its own Controller. Each Controller is dedicated to that single task by calling different sets of methods on the same Model.

There are some people, however, who think that this group of tasks represents a single Use Case and therefore build a single Controller to handle all of these tasks. I gave up this idea in the 1980s when I realised the advantages of breaking it down into smaller units as documented in Component Design - Large and Complex vs. Small and Simple. A Controller which is responsible for handling multiple tasks is, IMHO, breaking the Single Responsibility Principle and should therefore be avoided. My implementation uses a separate Controller for each task, but instead of hard-coding the Model name within the Controller I use a form of Dependency Injection to pass the Model name to the Controller. This means that I can use the same Controller to perform the same task on any Model in my application, and as I currently have over 350 different Models that is a HUGE amount of reusable code.

My library of reusable Controllers goes far beyond the six shown above. I currently have over 40 which are documented in Transaction Patterns for Web Applications. I have also automated the creation of new tasks by having a function where the developer can select a database table (Model) select a Transaction Pattern (Controller) then press a button to create all the necessary scripts for perform that task. Because each task is also a separate entry in the MENU database it therefore allows all access to the task to be controlled by the framework. This would be more difficult if multiple tasks were performed by the same Controller.

A Controller which is responsible for more than one View

I have seen several code samples on various blogs which show where a Controller can choose from a variety of different views at runtime. This again is a violation of the Single Responsibility Principle. In my implementation each View requires its own dedicated Controller, and each Controller can only ever be responsible for no more than one View. I say "no more than one" as a small number of my Controllers do not actually have a View - they are called to perform a task, they do it, and when it is done they return control to the calling form where the results can be displayed.

You should be ale to see that by following a reasonable interpretation of the Single Responsibility Principle I have been able to create small but highly specialised components which are completely reusable. This in turn makes it easier for me to create new components and maintain existing ones. If you cannot match my levels of productivity then any complaint that my implementation of MVC is somehow wrong or inferior will be met by howls of laughter.

Modified XSL (screen) Structure file
to change the way that the 'align' and 'valign' attributes are handled in LIST screens as they are poorly supported in most browsers, and not supported at all in HTML5.