web application design patterns. large scale architectures early systems were monolithic...

29
Web Application Design Patterns

Upload: hester-carpenter

Post on 04-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Web ApplicationDesign Patterns

Large Scale Architectures

• Early systems were monolithic applications– Large and hard to maintain

• Then came the client-server applications– Had to design client, server and protocol

• WWW has changed things– Standard extensible client– Standard server platform– Standard protocol

Design Patterns

• Many ways to write applications• Design Patterns suggest structure

– Learn from other’s experiences– Best practices– Best performance– Avoid pitfalls

The Model-View-Controller Architecture

Model

View

Controller

Model-View-Controller

• Architecture for interactive apps– introduced by Smalltalk developers at PARC

• Partitions application so that it is– scalable– maintainable

ModelView

Controller

Model

• Information the application is manipulating• Data representation of “real” world objects

– “circuit” for a CAD program• logic gates and wires connecting them

– shapes in a drawing program• geometry and color

– database

View

• Implements visual display of model• May have multiple views

– e.g., shape view and numerical view

• When model is changed notify views– so view can change later (e.g., adding new

item)

ModelView

Controller

Controller

• Receives all input events from user• Decides what they mean & what to

do

ModelView

Controller

Controller Communication

• Communicates with view – determines which objects are being manipulated

• e.g., which object was selected with mouse click

• Calls model methods to make changes– model makes change and notifies views to

update

ModelView

Controller

Model

View1

Controller

Multiple Views & Controllers

• View & controller tightly intertwined– lots of communication between the two

• Almost always occur in Controller-View groupings– i.e., for each view group need a separate controller

• Separate & group by functionView2

View3

Controller

View4

Why MVC?• Combining MVC into one class or using

global variables will not scale. Why?– model may have more than one view

• each different & needing update on model changes

• Separation eases maintenance. Why?– easy to add a new view later

• may need new model info, but old views still work

– can change a view later• e.g., draw shapes in 3-d

– recall that the view handles selection

MVC on the Web

• Latency and Bandwidth• Granularity of control• Granularity of messages• Scalability• Concurrency• Security

MVC on the Web

Model

View

Controller

Model-view interaction meansDB code in viewview code in model

- Messy & difficult to maintain

* Controller interacts with data access object

Inserting Data Access Objects

ApplicationObject

Data Access Object

ValueObject

Model

View1

Controller

View only needs to know format of Value Object and API of controller

Roles

• Application Objects– Encapsulate the business rules– Demarcate transactions

• Value Objects– Simply carry values from the model– Communicated to views

• Data Access Objects– Encapsulate interaction with information source (database)– Designed to work with different Application Objects

<?phpclass DAO{ private $link; private $db;

public function __construct($host, $dbname) { $link = mysql_connect($host); $db = mysql_select_db($dbname, $link); if (!$db) { die("Unable to connect to database\n"); } }

public function getPeople() { $query = "select * from QuinnsTable"; if ($result = mysql_query($query)) { $i = 0; while ($data = mysql_fetch_object($result)) { $people[$i] = $data; $i++; } return $people; } else { // Check result$message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);

} }}

?>

<html><head><title>MYSQL in PHP</title></head><body><h1>Using MYSQL in PHP</h1>

<?php

require "DAO.php";

$dao = new DAO('', 'test');$people = $dao->getPeople();

echo "<h3>Your Query Returned</h3>";echo "<ul>";foreach ($people as $person){ $n = $person->name; $a = $person->address; $p = $person->phone; echo "<li>Name = $n, Address = $a, Phone = $p\n";}echo "</ul>";

?>

</body></html>

Application Design

• Many interactive Web applications are structured as brittle collections of interdependent Web pages. Such applications can be hard to maintain:– When a page is moved, any links to the page must

be updated.– When a set of pages need to be password-protected,

various configuration files need to be modified, or the pages themselves need to include new functionality.

– When a page needs a new layout, the pages' functions must be rearranged.

The Front Controller

FrontController

View 1

View 2

View 3

View 4

Client

Helperclass

Helperclass

Helperclass

Front Controller

• Funnel all client requests through a front controller • Centralize Functions

– view selection, – security, and – templating

• Applies these functions consistently across all pages or views

• When the behavior of these functions need to change, only a small area of the application needs to be changed: – the controller and its helper classes.

<?php// Note that there is no html in this and no printing

session_start();

if(isset($_REQUEST['name'])){ $_SESSION['name'] = $_REQUEST['name']; $_SESSION[‘lastpage’] = 1}if(isset($_REQUEST['address'])){ $_SESSION['address'] = $_REQUEST['address'] $_SESSION[‘lastpage’] = 2;}

if (isset($_SESSION['lastpage'])){ switch ($_SESSION['lastpage']) { case '1': include ('View2.php'); break; case '2': include ('View3.php'); session_destroy(); break; }}else{ include ('View1.php');}?>

### View1.php ###<?phpinclude("header.php");?>

<h1>View 1</h1><form action="controller.php" method="POST">Please enter your name: <input type="text" name="name"><input type="submit" value="Submit"></form>

<?phpinclude("footer.php");?>

### View2.php ###<?phpinclude("header.php");?>

<h1>View 2</h1><form action="controller.php" method="POST">Please enter your address: <input type="text" name=”address"><input type="submit" value="Submit"></form>

<?phpinclude("footer.php");?>

Participants• FrontController

– translates user requests and dispatches them as application events.

– selects Views for the user based on application state.– applies templates and enforces security across all Views.

• Views – each View sends requests to the FrontController, whenever

it would have otherwise communicated with another View.• The process

– A client sends a request (through a view) to the FrontController.

– The FrontController dispatches the request as an application event, and selects an appropriate view to be displayed on client.

– The FrontController may also apply a transformation or enforce a policy on the selected view.

Benefits of Front Controller

• Navigation is easier to understand and configure. – Because view selection is centralized in the front

controller, you only have to look at the controller to understand the site navigation. Also, you only need to modify the controller in order to change the navigation.

• Views are handled consistently. – Since the front controller handles view selection, it can

consistently apply templating and security policies across all views. Also, it is easier to configure the behaviors of these functions, since only the controller needs to be modified.

• Views can be easily changed and reused. – Since views communicate only with the front controller,

there are no dependencies between views. This allows views, and even the front controller, to be varied and reused independently.

Consider• Complexity shifts to the front controller.

– The complexity of interaction between view components is traded for complexity in the front controller. Consequently, as an application grows, the controller can be harder to maintain.

• Bypassing the front controller for access to areas with static content. – The Front Controller pattern is applicable to sites with

complex navigation through dynamic content. However, it is possible that such a site may also have areas containing largely static content; it would be overkill to service these areas with a front controller.

– The front controller should be configured not to handle requests for areas with static content. This can be accomplished by placing static content in a namespace that is not serviced by the front controller.

Duplicate Form Submission

• Protect against hitting back button and resubmitting form information

• Synchronizer (or Déjà vu) Token– Set token in user’s session and include with each

form submission– Update token in user’s session when submission

takes place

• Can also use a synchronizer token to direct flow through site.– When a page is accessed, update/check synchronizer

token

Synchronizer Token

• Generate token upon sending form– Include in the form– Also include in the session

• Compare token when data is returned

• Change token when data is submitted

Data Validation

• Client validation vs Server validation• Client

– Simple validation using Javascript– Don’t rely on because client side languages can be

disabled• Server

– Validate as you extract information from the form– Error Handling

• Error Vector in session• As errors happen, put them in vector• Forward right back to current page

– Page always displays errors• Errors are best noted near the field where the error occurred.

Validation

• Consider validation based on abstract types

• Separate the validation of the model data from the controller logic

• Validation is more generic

controller

Model

validate

or

Other Design Issues

• Remove Conversions from view– Use helper classes

• Handling Forgotten Passwords– User Information should contain a secure

email address.– Email password to address– This assumes that if user has lost control of

email, they have more serious problems than a forgotten password.

– PHP Mail API