Presentation is loading. Please wait.

Presentation is loading. Please wait.

MVC, Model, View and Controller ISYS 475. The three components in a database application 1. Presentation – user interface Menus, forms, reports, etc 2.

Similar presentations

Presentation on theme: "MVC, Model, View and Controller ISYS 475. The three components in a database application 1. Presentation – user interface Menus, forms, reports, etc 2."— Presentation transcript:

1 MVC, Model, View and Controller ISYS 475

2 The three components in a database application 1. Presentation – user interface Menus, forms, reports, etc 2. Processing logic Business rules 3. 3.Data Access logic

3 The Model, View AND Controller, MVC Design Pattern The MVC design is a way of breaking an application into three parts: the model, the view, and the controller. – Input --> Processing --> Output – Controller --> Model --> View

4 Model The model represents enterprise data and the business rules that govern access to and updates of this data. 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.

5 View A view is some form of visualization of the state of the model that may generate HTML or PDF output. The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented.

6 Controller 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. The controller is responsible for mapping end- user action to application response. 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.


8 Concepts related to MVC Program/Data Independence DRY, Don’t Repeat Yourself Separation of presentation (interface) and processing logic

9 Program-data dependence When file structure changed, all programs that access the file must be modified to conform to the new file structure.

10 A COBOL Program Example IDENTIFICATION DIVISION. AUTHOR. Michael Coughlan. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT“ ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD StudentFile. 01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(4). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Gender PIC X. PROCEDURE DIVISION. Begin. OPEN OUTPUT StudentFile DISPLAY "Enter student details using template below. Enter no data to end." PERFORM GetStudentDetails PERFORM UNTIL StudentDetails = SPACES WRITE StudentDetails PERFORM GetStudentDetails END-PERFORM CLOSE StudentFile STOP RUN.

11 Program-data independence demo Microsoft Asp.Net data binding protected void Page_Load(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); GridView1.DataSource = objDataReader; GridView1.DataBind(); }

12 This program does not support program/data independence query($query); echo $customers->rowCount(). " rows returned."; echo " ". " CID ". " CName ". " City ". " Rating "; while ($customer = $customers->fetch()){ $cid=$customer["cid"]; $Cname=$customer["cname"]; $City=$customer["city"]; $Rating=$customer["rating"]; echo " $cid ". " $Cname ". " $City ". " $Rating "; } echo " "; } catch (Exception $e) { $error_message = $e->getMessage(); echo " Error message: $error_message "; } ?>

13 Supporting Program/Data Independence query($query); $customers->setFetchMode(PDO::FETCH_ASSOC); $AllCustomers=$customers->fetchAll(); if (count($AllCustomers)==0) echo "No record selected"; else { echo " "; foreach ($AllCustomers[0] as $field=>$value) { echo " $field "; } echo " "; foreach ($AllCustomers as $customer) { echo " "; foreach ($customer as $field=>$value) { echo " $value "; } } echo " "; } catch (Exception $e) { $error_message = $e->getMessage(); echo " Error message: $error_message "; } ?>

14 DRY, Don’t Repeat Yourself DRY is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. Also known as Single Source of Truth, this philosophy is prevalent in model-driven architectures, in which software artifacts are derived from a central object model. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."

15 Some Influences of DRY 1. Using template: – Example, a method to show records of a table. 2. Server-side include: – PHP require, include – Example: applying the same header and footer to all pages.

16 Example of Using Template query($query); $rows->setFetchMode(PDO::FETCH_ASSOC); $AllRows=$rows->fetchAll(); if (count($AllRows)==0) echo "No record selected"; else { echo "Records of the $tableName table "; echo " "; foreach ($AllRows[0] as $field=>$value) { echo " $field "; } echo " "; foreach ($AllRows as $row) { echo " "; foreach ($row as $field=>$value) { echo " $value "; } } echo " "; } showTable("customers"); showTable("products"); ?>

17 Example of Server-side include:Header/Footer Assuming every page of your website follows the same design theme for page header and footer. – 1. Create a file called header.php. In this file you will hold all of your page design that comes before your content. – 2.Next make a file called footer.php. This file will contain all of the site design information that goes below the content. – 3.Finally create the content pages for your site. In this file you will: 1.Call the header file 2.Put in the page specific content 3.Call the footer file

18 Header.php (A PHP file) Welcome to My Site My Site menu goes here Link 1 | Link 2 | Link 3

19 footer.php (a PHP file) Copyright 2013 My Site

20 Content.php (PHP web page) This is the first page Here is the specific content of this page....

21 One Implementation of the MVC Pattern

22 Page Controller Example: Separation of presentation from processing logic ASP.Net webform – In ASP.NET pages, the user interface programming is divided into two distinct pieces: The visual element is called the Web Forms page. The page consists of a file containing static HTML or ASP.NET server controls, or both simultaneously. The logic for the Web Forms page consists of code that you create to interact with the form. The programming logic resides in a file that is separate from the user interface file. This file, referred to as the code-behind file. – The controller manages events. Benefit: the application logic is not combined with the low-level code that manages the event dispatching and is easy to understand.

23 Example

24 Webform Page Enter name:

25 Code-behind file protected void Button1_Click(object sender, EventArgs e) { Label1.Text="Hello, " + TextBox1.Text + "!"; }

26 PHP Page Controller HTML page to present the view The mapping of the request to the file is performed by the web server PHP script implement the logic: –

27 Front Controller The Front Controller provides a centralized entry point for handling requests.

28 MVC Demo

29 Entry point: index.php – Define a controller object – Every actions first comes to this page Model: – Customer class, Order class View: Based on the model Controller: determine the view to display

30 An Example of Generating Entity Class from Database Schema

31 MySQL Information_Schema table mns-table.html mns-table.html Example: To select the columns from the customers table of the salesdb database: mysql> select column_name -> from information_schema.columns -> where table_name='customers' and table_schema='salesdb'; | column_name | | cid | | cname | | rating | | city | rows in set (0.02 sec)

32 Use PHP fopen to Create a Class (text) File fopen: The fopen() function opens a file or URL. fopen(filename,mode) – Filename: Specifies the file or URL to open – Mode: "r" (Read only. Starts at the beginning of the file) "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist) fwrite(resource $handle, string $string): writes the contents of string to the file stream pointed to by handle. fclose(resource $handle): Closes an open file.

33 Example $f = fopen("file.txt", "w"); fwrite($f, "TEXT TO WRITE"); fclose($f);

34 baseClass.php: A class with all field names retrieved from mySQL information Schema. class baseClass { public $fieldNames; function __construct() { $db = new PDO('mysql:host=localhost;dbname=salesdb', 'root', ''); $query="select column_name from information_schema.columns where table_name='customers' and table_schema='salesdb';"; $results = $db->query($query); $counter=0; //Generate a class with field names as properties $f = fopen("customerBase.php", "w"); fwrite($f,"fetch()) { $this->fieldNames[$counter]= $record[0]; fwrite($f, "public $$record[0]; "); ++$counter; } fwrite($f, "} ?>"); fclose($f); }

35 Generated customerBase.php

36 Customer Class require 'customerBase.php'; class customer extends customerBase { public $fieldValues; public function getCustomerData($searchID){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM customers WHERE CID='". $searchID. "'"; $customers = $db->query($query); $customers->setFetchMode(PDO::FETCH_NUM); return ($this->fieldValues=$customers->fetch()); } public function addNewCustomer(){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $queryINS = "insert into customers value("; for($i=0;$i fieldNames)-1;$i++) { $queryINS=$queryINS. "?,"; } $queryINS=$queryINS. "?)"; $stmt=$db->prepare($queryINS); return ($stmt->execute($this->fieldValues)) ; }

37 Using Customer Class getCustomerData("C1"); var_dump ($mycust->fieldValues); var_dump($mycust->fieldNames); $mycust->fieldValues[0]="X"; $mycust->fieldValues[1]="X"; $mycust->fieldValues[2]="X"; $mycust->fieldValues[3]="X"; if ($mycust->addNewCustomer()) echo "adding successful!"; else echo "adding not succesful!"; ?>

Download ppt "MVC, Model, View and Controller ISYS 475. The three components in a database application 1. Presentation – user interface Menus, forms, reports, etc 2."

Similar presentations

Ads by Google