Saturday, 5 January 2013

Why develop n-Tier Applications

New or junior php developers are always asking what they should be doing to improve their code which has led me to write the following post about n-Tier development. So what is n-Tier development,  N-Tier development is splitting your application into different sections to allow ease of future development.

For example if you were storing data in an array for your application then you would state that the php application is encapsulated in a single Tier.  Once you move to storing your data in another location separate from the php language like a database or data files.  That you process either through a database connection or through an import function.  You have moved to a 2 Tier application.  All good so far as this is where most developers will get to quite quickly.  Lets talk about 3-Tiers of application development,

So you have 

1) Database
2) Application 
But what is the third Tier???

The third Tier is presentation and by splitting your application into two distinct pieces you can get your third tier.Most applications have a business logic and a presentation logic and most young developers have these mixed through out their code.  Meaning that future changes to the system will either require a rewrite of a large complex function so that you can present two views or what normally happens is that the next developer takes a copy of function A and calls it B and then makes B do what they want.  So whats the problem with that ?  Simple if there is a fundamental flaw or security hole found in function A then you have to also know that you must fix B as wellTake for example the following small bit of code


function hello($name){ 
   $name = strtoupper($name);
   print ">>>Hello [$name] <<<";

As you can see this function renders the name in capitals and puts  angle brackets around the statement.

now lets say that we want to do the same thing but changing the presentation to be square brackets  would you create a new function our would it have been better to write it a different way to start with.

print ">>>" . hello("world") ."<<<";
print "[[[" . hello("world") ."]]]";

function hello($name){ 
   return strtoupper($name);

As you can now see the presentation is separate from the business logic.  the code is simpler as you have removed the presentation logic to a different location.

I was asked for example code so here you go

No comments:

Post a Comment