Back to Papers and Articles
Separation of Business Logic from Presentation Logic in Web Applications (ASP.NET and PHP)
Copyright 2003 Paragon Corporation   ( July 19, 2003)


  • How these objects are stored
  • How these objects interact with each other - e.g. a bank account must have an owner and a bank holder's portfolio is the sum of his accounts
  • Who can access and update these objects

Business Logic is often broken further into two components in the Model-View-Controller (MVC) paradigm -- the Model, which defines how the data will be stored and retrieved; and the Controller, which controls the interaction between the Model and the View. For simplicity and practicality, we are not going to make this distinction. In many cases, we feel this distinction is unnecessary because the control flow pattern of the Model and the Controller is very similar and conceived of at the same time. So the benefits of separation or thinking of them as independent are often mitigated by the hassle of the extra layer.

When we speak about Presentation Logic we mean how we display these objects to a user. E.g do we have a drop down list or a popup screen? Do we display accounts in a list format and have the user pick which one to edit? etc. This is often referred to as the View in the MVC paradigm.

It is often difficult to determine where business logic ends and presentation logic begins. How you model your application often dictates what is possible in the user interface. Sometimes the business and presentation logic is so intricate and dependent on each other that the two get intertwined with each other. Sometimes it is often difficult or impossible to separate the two. In most other cases, separating the two is just a matter of discipline.

Why should we separate Business Logic from Presentation Logic

There are several reasons why separating business logic from presentation logic is desired. Below are a couple of reasons why we do it.

  • The kind of programming you do for each part and sometimes the language you do it in are different. Separating the two allows one to use the best tools for that particular part. For example if you are programming a user interface screen - the kinds of things you are concerned with are paging - e.g. how many records to show on a page, widths of forms, colors, readability etc. There is also the need to see the screen as you are developing and to position the items. On the business side you are not so concerned about visuals - you need to get the data from somewhere and you need to control what data is loaded, and how that data is updated. If you change your programming languages next year, it is much easier to reuse old code when it is separated. E.g your presentation would be mostly html or xml which can be easily refitted with a different model.

  • The two parts - business logic and presentation logic - do not always occur at the same time. For example, often times you design the screens first and then cut in the business logic later. Separating the two minimizes time dependency and allows for concurrent development. You can work on each part independently and then integrate them later or integrate in an iterative fashion.

  • Separation of Workforce: This is important for big organizations with very specialized people, but is less important for small shops where often the programming of all parts is done by the same person.

  • Separation of Thought and Readability of code: It is easier to read business logic that is not intermingled with presentation logic. Similarly, it is easier to look at the presentation of a screen or read html code without having to sift through the database and security logic. Case in point if you look at standard ASP,JSP, or PHP coding, you will often see structures with things like looping thru a dataset and spitting out results in html. If this happens it's hard to tell when an html tag is missing or find the logic that tells where the data is coming from.

Examples Using ASP.NET and PHP

There are several approaches to achieving this separation in modern languages. In this section we will describe two such approaches that are commonly used.

The first approach is the inheritance way which is commonly used in ASP.NET and is called Code-behind by Microsoft. The second approach is the template approach which is used in several web languages such as PHP and Java Servlets (WebMacro), Apache (Velocity). We will discuss a particular implementation in PHP that uses the Smarty Template engine and the PHP ADODB lib and a particular approach of doing code-behind (not using Visual Studio.NET).

In the inheritance approach - the presentation (the web page) is a subclass of another class which contains the business logic. You can think of it as a creature with eyes and skin that inherits its other features from another class, but then tacks on eyes and skin.

In the template approach – the presentation is merely a visual object that is controlled by something else – An analogy would be that of a puppet master to his puppets. A puppet master can tack on any puppet he wants at anytime, but usually has his favorites that he likes to work with. Similarly several puppet masters can share the same set of puppets. In this style the template (or presentation) is the puppet and the puppet master is the business logic class.

There are advantages and disadvantages to both. In the inheritance approach there is a greater coupling which for one makes debugging logical errors a little easier. However another little creature can’t come along and easily say "I have the same list of fields to show can I borrow your skin for a moment," as you can so easily in the template approach.

The other thing that makes ASP.Net's style different from the standard template approach is that ASP.NET instantiates all visual objects that are marked runat=server. This means that one can easily manipulate any property of a visual object - e.g the datagrid, data list etc. from the business logic page. In the template approach you would put markers in the template to do that so that you can stuff these markers at runtime. Again this is both a curse and a blessing. ASP.NET provides standardized properties you know will always be there e.g most objects can be hidden by setting the visible property to false, but if you need additional properties not defined, you need to create your own visual objects that inherit. The Smarty approach is a bit easier in this respect.

A big downside of ASP.NET approach is that it has a plethora of classes for visual objects. To become really proficient in it, you have to understand these classes (at the very minimal the datagrid, datalist, forms), what the events mean and how the events are triggered. Editors like Visual Studio.NET minimize a bit on the need to understand these, but they themselves are bewildering to understand and control just the way you want it, and when things go wrong - you really need to understand the Abstractions you are depending on.

Smarty is a particularly nice template engine; it stands out from the pack because it has an easily extensible plug-in architecture and comes with a lot of plug-ins that expedite common presentation issues such as generating a list, a dropdown list, radio button lists, calendar form controls etc. These plug-ins have similar counterparts to those you will find in ASP.NET, but they don't deviate as much from the standard HTML model so are much quicker to learn and a bit easier for html editors to digest.

Below is an example of how you would load data from a database and present it in an alternating colored row table in PHP/Smarty/ADODB vs. ASP.NET/ADO.NET.

Business Logic (mylist.php)
   3:Class MyList extends Smarty {
   4:    var $conn; //a database connection object
   5:    var $dbhost = "localhost";
   6:    var $dbuser = "me";
   7:    var $dbpass = "mypass";
   8:    var $dbname = "myname";
   9:    var $dbtype = "postgres";
  11:    function MyList(){
  12:        $this->loadList();
  13:    }
  15:    function connect(){
  16:    /**Returns a new ADODB connection object ***/
  17:        if (!isset($this->conn)) {
  18:           $this->conn = &ADONewConnection($this->db_type);
  19:            if (!$this->conn->PConnect($this->db_host, $this
    :->db_user,$this->db_pass, $this->db_name)) {
  20:                die("Cannot connect to server");
  21:                return false;
  22:            } 
  23:        }
  24:        $this->conn->SetFetchMode(ADODB_FETCH_ASSOC);
  25:        return true;
  26:    }
  28:    function loadList(){
  29:        $sql = "SELECT * FROM mylist order by listname";
  30:        if ($this->connect()){
  31:            $rs = $this->conn->Execute($sql);
  32:        }
  33:        $this->assign_by_ref("rs", $rs->GetRows());     
  34:        $rs->Close();
  35:        $this->conn->Close();
  36:        $this->display("MyList.tpl");
  37:    }
  40:new MyList();
MyList.tpl (Presentation Logic)
   1:{include file="header.tpl" title="My List"}     
   2:<TABLE border=1  width="550" cellpadding=2 cellspacing="0">
   4:    <TD>
   5:        <TABLE id=Table1 cellSpacing=5 cellPadding=5 width="100%" align=center border=0 >
   6:        <TR>
   7:            <TD class=FormHeader colSpan=10>My List</TD>
   8:        </TR>
   9:        <TR class="GridHeader"><TD>List Name</TD><TD>List Total</TD></TR>
  10:        {section name=sec loop=$rs}
  11:            <TR class="{cycle values="GridItem,GridAlternatingItem"}">
  12:                <TD><a href="mylistdetail.php?mylistid={$rs[sec].listid}">{$rs[sec].listname}</a></TD>
  13:                <TD>{$rs[sec].listtotal}</TD>
  14:            </TR>
  15:        {/section}  
  16:        </TABLE>
  17:    </TD>

Back to Papers and Articles