Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Spring 2020

# Session 13: Server-Side, Part 2

Harvard Extension School
Spring 2020

Course Web Site: http://cscie12.dce.harvard.edu/

Instructor email: david_heitmeyer@harvard.edu
Course staff email: cscie12@dce.harvard.edu

### Topics

1. Building Pages from Parts: An Introduction to PHP
2. Web Development
3. PHP Example with Courses from Database
4. Using "View" templates - Model, View, * (MV*) Design Pattern
5. {{Mustache}} Templates
6. Hello! Greeting, Improved

slide1 slide2 slide3 slide4 slide5 slide6 slide7 slide8 slide9 slide10 slide11 slide12 slide13 slide14 slide15 slide16 slide17 slide18 slide19 slide20 slide21 slide22 slide23 slide24 slide25 slide26 slide27 slide28 slide29

- img
- img
- img
- img
- img

## Building Pages from Parts: An Introduction to PHP

### Review of HTTP Request/Response

### Pages from Parts

## Building a Page from Parts

### Why?

- Common elements of site are in one place and included throughout the site
  Useful to include documents or information that is used repeatedly throughout a site, such as common headers, footers, and navigation elements. You can change these chunks in one place and have an effect on the entire site!
- Documents (or parts of pages) that change often
  Useful to include documents or information that change frequently; only the "included" file needs to be updated, not the page itself. Also the person or program editing the file need only have permissions to edit the "included" file, not the actual HTML document that includes it; only the data in the "include" file needs to be written, not the entire HTML page.
- Document Information
  Useful to include information specific about a document, such as last modified date, URI, size.

### Techniques

- PHP and file include
- Apache Server Side Includes (SSI)

## Iroquois Constitution

Iroquois Constitution

Iroquois Constitution Zip File containing HTML, CSS, and "Include" files.

## PHP: Hypertext Processor

- PHP: Hypertext Processor

From the PHP manual:

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

### PHP Example

hello.php

    <?php
      $greeting = "Hello, World!";
    ?>
    <html lang="en">
    <head><title>Hello</title></head>
    <body>
    <h1><?php echo($greeting) ?></h1>
    </body>
    </html>

## File Includes with PHP

    <!DOCTYPE html>
    <html>
      <head>
        <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
       <?php include("inc/htmlhead.php"); ?>
      </head>
      <body id="part1">
       <?php include("inc/header.php"); ?>
       <?php include("inc/nav.php"); ?>
        <div id="main">
       <?php include("inc/content1.php"); ?>
        </div>
        <?php include("inc/footer.php"); ?>
      </body>
    </html>

### Files

    |-- 1.php
    |-- 10.php
    |-- 11.php
    |-- 12.php
    |-- 13.php
    |-- 14.php
    |-- 15.php
    |-- 16.php
    |-- 2.php
    |-- 3.php
    |-- 4.php
    |-- 5.php
    |-- 6.php
    |-- 7.php
    |-- 8.php
    |-- 9.php
    |-- inc
    |   |-- content1.php
    |   |-- content10.php
    |   |-- content11.php
    |   |-- content12.php
    |   |-- content13.php
    |   |-- content14.php
    |   |-- content15.php
    |   |-- content16.php
    |   |-- content2.php
    |   |-- content3.php
    |   |-- content4.php
    |   |-- content5.php
    |   |-- content6.php
    |   |-- content7.php
    |   |-- content8.php
    |   |-- content9.php
    |   |-- footer.php
    |   |-- header.php
    |   |-- htmlhead.php
    |   |-- nav.php
    |   `-- validate.php
    |-- js
    |   `-- highlightnavigation.js
    `-- style.css

## Parts that Build the Page

### Starting File (1.php)

    <!DOCTYPE html>
    <html>
      <head>
        <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
        <?php include("inc/htmlhead.php"); ?>
      </head>
      <body id="part1">
        <?php include("inc/header.php"); ?>
        <?php include("inc/nav.php"); ?>
        <div id="main">
          <?php include("inc/content1.php"); ?>
        </div>
        <?php include("inc/footer.php"); ?>
      </body>
    </html>

### HTML Head Content - htmlhead.php

    <link rel="stylesheet" type="text/css" href="style.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"> </script>
    <script type="text/javascript" src="js/highlightnavigation.js"> </script>

### Header - header.php

    <div id="header"><h1>Constitution of the Iroquois Nations</h1></div>

### Navigation - nav.php

    <div id="navigation">
    <ul id="mainnav">
    <li id="navpart1"><a href="1.php">The Great Binding Law, Gayanashagowa</a></li>
    <li id="navpart2"><a href="2.php">Rights, Duties and Qualifications of Lords</a></li>
    <li id="navpart3"><a href="3.php">Election of Pine Tree Chiefs</a></li>
    <li id="navpart4"><a href="4.php">Names, Duties and Rights of War Chiefs</a></li>
    <li id="navpart5"><a href="5.php">Clans and Consanguinity</a></li>
    <li id="navpart6"><a href="6.php">Official Symbolism</a></li>
    <li id="navpart7"><a href="7.php">Laws of Adoption</a></li>
    <li id="navpart8"><a href="8.php">Laws of Emigration</a></li>
    <li id="navpart9"><a href="9.php">Rights of Foreign Nations</a></li>
    <li id="navpart10"><a href="10.php">Rights and Powers of War</a></li>
    <li id="navpart11"><a href="11.php">Treason or Secession of a Nation</a></li>
    <li id="navpart12"><a href="12.php">Rights of the People of the Five Nations</a></li>
    <li id="navpart13"><a href="13.php">Religious Ceremonies Protected</a></li>
    <li id="navpart14"><a href="14.php">The Installation Song</a></li>
    <li id="navpart15"><a href="15.php">Protection of the House</a></li>
    <li id="navpart16"><a href="16.php">Funeral Addresses</a></li>
    </ul>
    </div>

### Footer - footer.php

    <div id="footer">
    Text form prepared by Gerald Murphy (The Cleveland Free-Net - aa300). Distributed by the Cybercasting Services Division of the National Public Telecomputing Network. Rendered into HTML by <a href="mailto:jon.roland@the-spa.com">Jon Roland</a> of the Constitution Society.  (NPTN). Permission is hereby granted to download, reprint, and/or otherwise redistribute this file, provided appropriate point of origin credit is given to the preparer(s), the National Public Telecomputing Network and the Constitution Society.
    <div class="note">
    <p>Additional information about the Iroquois nations and their constitution are available:</p>
    <ul>
    <li><a href="http://www.sixnations.org/">Haudenosaunee:  People Building a Long House</a></li>
    <li><a href="http://www.tuscaroras.com/graydeer/influenc/page1.htm">The Influence of the Great Law of Peace on the the United States constitution:  an Haudenosaunee (Iroquois) Perspective</a></li>
    <li><a href="http://www.ratical.org/many_worlds/6Nations/index.html">The Six Nations:  Oldest Living Participatory Democracy on Earth</a></li>
    <li><a href="http://www.carnegiemuseums.org/cmnh/exhibits/north-south-east-west/iroquois/">The Iroquois nations of the Northeast</a></li>
    <li><a href="http://www.iroquoismuseum.org/">Iroquois Indian Museum</a></li>
    </ul>
    </div>
    <p>
      <?php include("validate.php"); ?>
    </p>
    </div>

## Recommendation: Keep files well-formed

### Don't do this: Breaking a page in half

This technique is not recommended. The first include file contains the top "half" of the page; the content follows; the second include file contains the bottom "half" of the page. In this technique, the `html` ,`body`, and perhaps other elements are started in the "top half" and their end tags are in "bottom half." The page delivered to the browser does validate, but the individual parts on the server are not well-formed, which can cause some confusion when editing a file.

    <?php include("header-tophalf.html"); ?>
      Lorem ipsum dolor sit amet, consectetuer adipiscing ...
    <?php include("footer-bottomhalf.html"); ?>

### Keeping things well-formed

    <!DOCTYPE html>
    <html>
      <head>
        <title>Lecture Notes</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
      </head>
      <body>
        <div id="header">
          <?php include("inc/header.php") ?>
        </div>
        <div id="navigation">
          <?php include("inc/nav.php") ?>
        </div>
        <div id="main">
          Lorem ipsum dolor sit amet, consectetuer adipiscing ...
        </div>
      </body>
    </html>

## Web Development

Language | Frameworks/Platforms
--- | ---
JavaScript | Node, Angular, Backbone, Ember
PHP | Laravel, Symfony, CodeIgniter, CakePHP CMS: Drupal, Joomla, Concrete5, GetSimple
Python | Django, CherryPy, Flask, Zope, Plone
Ruby | Rails
Perl | Catalyst, Dancer, Mojolicious
Java | Struts, Sling, JSF, Wicket, Tapestry, Grails
C# | ASP.NET, ASP.NET MVC Framework, others

## Dynamic Content

- Internal and persistent (e.g. PHP in Apache)
- External and persistent (e.g. FastCGI)

## Dynamic Content: How does it look?

- program that outputs Web content
  programs with HTML embedded
- Web content that has embedded programming
  HTML with programs embedded
- Separation of Concerns (SOC)
  MV*, Model-View-* (Controller, Presenter, ModelView, Whatever).

## Web Program Examples

Markup or content is embedded within a program; program embedded into markup

### first.pl - Perl

first.pl

    #!/usr/local/bin/perl
    print "Content-type: text/html\n\n";
    print "<html><body><h1>Hello, World!</h1></body></html>";

### first.py - Python

first.py

    #!/usr/bin/python
    print "Content-type: text/html\n\n";
    print "<html><head><title>Hello World!</title></head>";
    print "<body><h1>Hello, World!</h1></body></html>";

### first.php - PHP

first.php

    <?php
    echo('<html><head><title>First PHP</title></head><body>');
    echo('<h1>Hello!</h1>');
    echo('</body></html>');
    ?>

### second.php - PHP

second.php
program statements within markup

    <?php
          $title = "Hello World!";
    ?>
    <!DOCTYPE html>
      <head>
        <meta charset="utf-8" />
        <title><?php echo($title) ?></title>
      </head>
      <body>
        <h1><?php echo($title) ?></h1>
      </body>
    </html>

## A Personal Greeting

- third.php
- third.php?name=John%20Harvard

    <?php
          $name = $_GET["name"];
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Greeting Page</title>
      </head>
      <body>
        <h1>Hello, <?php echo($name) ?>!</h1>
      </body>
    </html>

## A Personal Greeting

Without a "name", present the user a form. With a name, provide a greeting.

- fourth.php
- fourth.php?name=John%20Harvard

    <?php
          $name = $_GET["name"];
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8"/>
        <title>Greeting Page</title>
      </head>
      <body>
        <?php
        if ($name) {
          echo("<h1>Hello, $name!</h1>");
        } else {
          echo('<h1><label for="input_name">Enter name:</label></h1>');
          echo('<form method="get">');
          echo('<input type="text" name="name" id="input_name"/>');
          echo('<br /><input type="submit" />');
          echo('<br /><input type="reset" />');
        }
    ?>
      </body>
    </html>

## PHP Example with Courses from Database

- http://cscie12.dce.harvard.edu/cgi/courses/departments.php

## FAS Course Data

### Data Table

Course data for Faculty of Arts & Sciences is in a mysql database on cscie12students (username: class; database name: coursecatalog)

SQL:

    describe courses

Terminal:

    cscie12students$ mysql -u class coursecatalog
    Welcome to the MySQL monitor.  Commands end with ; or \g.

    mysql> describe courses;
    +------------------------------+--------------+------+-----+---------+-------+
    | Field                        | Type         | Null | Key | Default | Extra |
    +------------------------------+--------------+------+-----+---------+-------+
    | acad_year                    | year(4)      | YES  |     | NULL    |       |
    | cat_num                      | int(9)       | YES  |     | NULL    |       |
    | offered                      | char(1)      | YES  |     | NULL    |       |
    | department_code              | varchar(15)  | YES  |     | NULL    |       |
    | department_short             | varchar(80)  | YES  |     | NULL    |       |
    | department_long              | varchar(200) | YES  |     | NULL    |       |
    | course_group_code            | varchar(10)  | YES  |     | NULL    |       |
    | course_group_long            | varchar(200) | YES  |     | NULL    |       |
    | num_int                      | int(9)       | YES  |     | NULL    |       |
    | num_char                     | varchar(15)  | YES  |     | NULL    |       |
    | term_pattern_code            | int(5)       | YES  |     | NULL    |       |
    | fall_term                    | char(1)      | YES  |     | NULL    |       |
    | spring_term                  | char(1)      | YES  |     | NULL    |       |
    | term                         | varchar(100) | YES  |     | NULL    |       |
    | title                        | text         | YES  |     | NULL    |       |
    | course_type                  | varchar(100) | YES  |     | NULL    |       |
    | course_level_code            | char(1)      | YES  |     | NULL    |       |
    | course_level                 | varchar(200) | YES  |     | NULL    |       |
    | credit_code                  | int(5)       | YES  |     | NULL    |       |
    | credit                       | varchar(50)  | YES  |     | NULL    |       |
    | instructor_approval_required | char(1)      | YES  |     | NULL    |       |
    | meeting_time                 | text         | YES  |     | NULL    |       |
    | faculty_text                 | text         | YES  |     | NULL    |       |
    | description                  | text         | YES  |     | NULL    |       |
    | prerequisites                | text         | YES  |     | NULL    |       |
    | notes                        | text         | YES  |     | NULL    |       |
    +------------------------------+--------------+------+-----+---------+-------+
    26 rows in set (0.00 sec)

### SQL

SQL:

    select distinct department_short from courses

Terminal:

    mysql> select distinct department_short from courses;
    +----------------------------------------------------------+
    | department_short                                         |
    +----------------------------------------------------------+
    | African and African American Studies                     |
    | American Studies                                         |
    | Anthropology                                             |
    | Architecture, Landscape Architecture, and Urban Planning |
    | Asian Studies Programs                                   |
    | Astronomy                                                |
    | Biological Sciences in Dental Medicine                   |
    | Biological Sciences in Public Health                     |
    | Biophysics                                               |
    | Biostatistics                                            |
    | Celtic Languages and Literatures                         |
    | Chemical Biology                                         |
    | Chemical and Physical Biology                            |
    | Chemistry and Chemical Biology                           |
    | Comparative Literature                                   |
    | Dramatic Arts                                            |
    | Earth and Planetary Sciences                             |
    | East Asian Languages and Civilizations                   |
    | Economics                                                |
    | Engineering and Applied Sciences                         |
    | English                                                  |
    | Environmental Science and Public Policy                  |
    | Expository Writing                                       |
    | Folklore and Mythology                                   |
    | Freshman Seminars                                        |
    | General Education                                        |
    | Germanic Languages and Literatures                       |
    | Global Health and Health Policy                          |
    | Government                                               |
    | Health Policy                                            |
    | History                                                  |
    | History and Literature                                   |
    | History of Art and Architecture                          |
    | History of Science                                       |
    | House Seminars                                           |
    | Human Evolutionary Biology                               |
    | Humanities                                               |
    | Life Sciences                                            |
    | Linguistics                                              |
    | Mathematics                                              |
    | Medical Sciences                                         |
    | Medieval Studies                                         |
    | Middle Eastern Studies                                   |
    | Mind, Brain, and Behavior                                |
    | Molecular and Cellular Biology                           |
    | Music                                                    |
    | Near Eastern Languages and Civilizations                 |
    | Neurobiology                                             |
    | No Department                                            |
    | Organismic and Evolutionary Biology                      |
    | Philosophy                                               |
    | Physical Sciences                                        |
    | Physics                                                  |
    | Psychology                                               |
    | Regional Studies - East Asia                             |
    | Romance Languages and Literatures                        |
    | Russia, Eastern Europe, and Central Asia                 |
    | Slavic Languages and Literatures                         |
    | Social Policy                                            |
    | Social Studies                                           |
    | Sociology                                                |
    | South Asian Studies                                      |
    | Special Concentrations                                   |
    | Statistics                                               |
    | Stem Cell and Regenerative Biology                       |
    | Studies of Women, Gender, and Sexuality                  |
    | Systems Biology                                          |
    | The Classics                                             |
    | The Study of Religion                                    |
    | Ukrainian Studies                                        |
    | Visual and Environmental Studies                         |
    +----------------------------------------------------------+
    71 rows in set (0.01 sec)

## PHP Script to Connect to Database and Get List of Departments

    #!/usr/bin/php
    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    // iterating through results
    while ($row = $result->fetch_assoc()){
      echo $row['department_code'];
      echo "\t";
      echo $row['department_short'];
      echo "\n";
    }
    ?>

### Output

[dheitmey@apophis courses]$ php dept-txt.php AAAS African and African American Studies AMER American Studies ANTH Anthropology URBP Architecture, Landscape Architecture, and Urban Planning ABEA Asian Studies Programs ASTR Astronomy BSDM Biological Sciences in Dental Medicine BSPH Biological Sciences in Public Health BIPH Biophysics BIST Biostatistics CELT Celtic Languages and Literatures CHPB Chemical and Physical Biology CHBI Chemical Biology CHEM Chemistry and Chemical Biology CPLT Comparative Literature DRAM Dramatic Arts E&PS Earth and Planetary Sciences EALC East Asian Languages and Civilizations ECON Economics DEAS Engineering and Applied Sciences ENGH English ESPP Environmental Science and Public Policy EXPO Expository Writing FOLK Folklore and Mythology FRSP Freshman Seminars GEN ED General Education GERM Germanic Languages and Literatures GLOBHLTH Global Health and Health Policy GOVM Government HPOL Health Policy HIST History HLIT History and Literature HAA History of Art and Architecture HSCI History of Science HSEM House Seminars HEB Human Evolutionary Biology HUM Humanities LSCI Life Sciences LING Linguistics MATH Mathematics MDSC Medical Sciences MDST Medieval Studies MEST Middle Eastern Studies MBB Mind, Brain, and Behavior MCB Molecular and Cellular Biology MUSC Music NELC Near Eastern Languages and Civilizations NEURO Neurobiology NODEPT No Department BIOE Organismic and Evolutionary Biology PHIL Philosophy PSCI Physical Sciences PHYS Physics PSYC Psychology RSEA Regional Studies - East Asia ROML Romance Languages and Literatures REECA Russia, Eastern Europe, and Central Asia SLAV Slavic Languages and Literatures SPOL Social Policy SOST Social Studies SOCL Sociology SAST South Asian Studies SPCN Special Concentrations STAT Statistics SCRB Stem Cell and Regenerative Biology WMGS Studies of Women, Gender, and Sexuality SBIO Systems Biology CLAS The Classics RELG The Study of Religion UKRA Ukrainian Studies VES Visual and Environmental Studies

## Turn this into HTML Output

    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    // iterating through results
    echo "<ul>\n";
    while ($row = $result->fetch_assoc()) {
      echo "<li>";
        echo $row['department_short'];
        echo "</li>\n";
     }
    echo "</ul>\n";
    ?>

## The entire "departments-simple.php"

- http://cscie12.dce.harvard.edu/cgi/courses/departments-simple.php

    <!DOCTYPE html>
    <html>
     <head>
      <title>Departments</title>
      <link rel="stylesheet" href="site.css" type="text/css"/>
     </head>
     <body>
    <h1>Faculty of Arts &amp; Sciences</h1>
    <h2>Departments</h2>

    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    // iterating through results
    echo "<ul>\n";
    while ($row = $result->fetch_assoc()) {
      echo "<li>";
        echo $row['department_short'];
        echo "</li>\n";
     }
    echo "</ul>\n";

    // Free resultset
    $result->free();
    // Close connection
    $mysqli->close();

    ?>

     </body>
    </html>

## Adding another view - Department Course Listings

Create another PHP file that displays course information based upon a department_code parameter.

- `courses.php` - take a "department_code" parameter and produce alist of courses for that department.

Need to link to to courses.php:

- courses.php?department_code=CHEM
- courses.php?department_code=MCB

Modify the department listing to include the hyperlink:

    <!DOCTYPE html>
    <html>
     <head>
      <title>Departments</title>
      <link rel="stylesheet" href="site.css" type="text/css"/>
     </head>
     <body>
    <h1>Faculty of Arts &amp; Sciences</h1>
    <h2>Departments</h2>
    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    // Printing results in HTML
    echo "<ul>\n";
    while ($row = $result->fetch_assoc()) {
      echo "<li>";
      echo "<a href=\"courses.php?department_code=$row[department_code]\">$row[department_short]</a>";
      echo "</li>\n";
    }
    echo "</ul>\n";

    // Free resultset
    $result->free();
    // Close connection
    $mysqli->close();

    ?>

    </body>
    </html>

## courses.php

- courses.php?department_code=CHEM
- courses.php?department_code=MCB

    \<!DOCTYPE html>
    <html>
     <head>
      <title>FAS Courses</title>
      <link rel="stylesheet" href="site.css" type="text/css"/>
     </head>
     <body>
    <h1>Faculty of Arts &amp; Sciences</h1>
    <p><a href="departments.php">Return to Department List</a></p>
    <h2>Department <?php echo $_GET['department_code'] ?></h2>
    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }
    $dept_code = $_GET['department_code'];
    $sqlescaped_dept_code = $mysqli->real_escape_string($dept_code);

    // Performing SQL query
    $query = 'SELECT course_group_long, num_int, num_char, term, title, description, faculty_text';
    $query .= ' from courses where department_code = ';
    $query .= "'".$sqlescaped_dept_code."'";
    $query .= ' order by course_group_long, num_int, num_char, title';

    $result = $mysqli->query($query);

    // Printing results in HTML
         echo "<table cellspacing='0' cellpadding='0'>\n";
    $i = 0;
         while ($row = $result->fetch_assoc()) {
           $class = $i++ % 2 ? 'evenrow' : 'oddrow' ;
           echo "\t<tr class='$class'>\n";
           echo "<td class='abbrev'>$row[course_group_long] $row[num_int] $row[num_char]</td>";
           echo "<td class='long'><strong>$row[title]</strong><br/>";
           echo "<span class='faculty'>$row[faculty_text]</span>";
           echo "<p class='description'>$row[description]</p></td>";
           echo "\t</tr>\n";
         }
    echo "</table>\n";

    // Free resultset
    $result->free();
    // Close connection
    $mysqli->close();
    ?>

    </body>
    </html>

## Using "View" templates - Model, View, * (MV*) Design Pattern

Variations: Controller, Presenter, ViewModel, Whatever

MVC design pattern separates:

- Model. data model
- View. user interface
- Controller. control and flow logic

You can adopt this design pattern regardless of language or server-architecture. Some frameworks make using MV* possible, some make it easy, some insist on it.

## PHP Smarty Templates

- Smarty
  is a Template Engine for PHP, which allows you to write Templates for your PHP data.

The template (departments.tpl):

    <!DOCTYPE html>
    <html>
     <head>
      <title>Departments</title>
      <link rel="stylesheet" href="site.css" type="text/css"/>
     </head>
    <body>
    <h1>Faculty of Arts &amp; Sciences</h1>
    <h2>Departments</h2>
      <ul>
      {foreach from=$dept item=d}
      <li>
          <a href="smarty-courses.php?department_code={$d.department_code}">{$d.department_short}</a>
      </li>
      {/foreach}
      </ul>
    </body>
    </html>

Get the departments: smarty-dept.php

    <?php
    /* ==================================================
        Database Stuff
       ================================================== */
    /// Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    $i=0;
    while ($row = $result->fetch_assoc()) {
      $results[$i++] = $row;
    }

    /* ==================================================
        Smarty Template Stuff
       ================================================== */
       require('/usr/local/lib/php/Smarty/Smarty.class.php');

       // create object
       $smarty = new Smarty;

       $smarty->template_dir = './smarty_templates';
       $smarty->compile_dir = '/tmp/smarty/templates_c';
       $smarty->cache_dir = '/tmp/smarty/cache';
       $smarty->config_dir = './smarty_configs';

       // assign some content. This would typically come from
       // a database or other source, but we'll use static
       // values for the purpose of this example.
       $smarty->assign('dept', $results);

       // display it
       $smarty->display('departments.tpl');

    /* ==================================================
        Cleanup
       ================================================== */
       // free and close
      $result->free();
      $mysqli->close();
    ?>

## Smarty Template for Courses

The template (courses.tpl):

    <!DOCTYPE html>
    <html>
     <head>
      <title>Departments</title>
      <link rel="stylesheet" href="site.css" type="text/css"/>
     </head>
     <body>
    <h1>Faculty of Arts &amp; Sciences</h1>
    <p><a href="smarty-dept.php">Return to Department List</a></p>
    <h2>Department {$department_code}</h2>
    <table cellspacing="0" cellpadding="0">
    {foreach from=$courses item=course name=courses}
    <tr class="{cycle values="row1,row2,row3,row4"}">
    <td class="abbrev">{$course.course_group_long} {$course.num_int}{$course.num_char}</td>
    <td class="long">
      <strong>{$course.title}</strong><br/>
      <span class="faculty">{$course.faculty_text}</span>
      <p class="description">
        {$course.description}
      </p>
    </td>
    </tr>
    {/foreach}
    </table>
    </body>
    </html>

Get the Courses for the CHEM department: smarty-courses.php?department_code=CHEM

The SQL:

    SELECT course_group_long,
                  num_int, num_char, term,
                  title, description

smarty-course.php:

    <?php
    /* ==================================================
        Database Stuff
       ================================================== */
       // Connecting, selecting database
         $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
         if ($mysqli->connect_errno) {
             echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
         }
       $dept_code = $_GET['department_code'];
       $sqlescaped_dept_code = $mysqli->real_escape_string($dept_code);

       // Performing SQL query
       $query = 'SELECT course_group_long, num_int, num_char, term, title, description, faculty_text';
       $query .= ' from courses where department_code = ';
       $query .= "'".$sqlescaped_dept_code."'";
       $query .= ' order by course_group_long, num_int, num_char, title';

       $result = $mysqli->query($query);

       $i = 0;
       while ($row = $result->fetch_assoc()) {
         $results[$i++] = $row;
       }

    /* ==================================================
        Smarty Template Stuff
       ================================================== */
       require('/usr/local/lib/php/Smarty/Smarty.class.php');

       // create object
       $smarty = new Smarty;
       // pass the results to the template
       $smarty->assign('courses', $results);
       $smarty->assign('department_code', $_GET['department_code']);

       $smarty->template_dir = './smarty_templates';
       $smarty->compile_dir = '/tmp/smarty/templates_c';
       $smarty->cache_dir = '/tmp/smarty/cache';
       $smarty->config_dir = './smarty_configs';

       // assign some content. This would typically come from
       // a database or other source, but we'll use static
       // values for the purpose of this example.
       $smarty->assign('dept', $results);

       // display it
       $smarty->display('courses.tpl');

    /* ==================================================
        Cleanup
       ================================================== */
       // Free resultset
       $result->free();

       // Closing connection
       $mysql->close();
    ?>

## {{Mustache}} Templates

{{mustache}} is another widely used template system for JavaScript (and other languages!).

## Mustache Departments

### Mustache Template

mustache-dept.php

### PHP

    <?php
    // Connecting, selecting database
      $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
      if ($mysqli->connect_errno) {
          echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
      }

    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $result = $mysqli->query($query);

    $i=0;
    while ($row = $result->fetch_assoc()) {
      $results[$i++] = $row;
    }

    $template_data['departments'] = $results;

    // Process with Mustache Template
    include('lib/Mustache.php');

    $m = new Mustache;
    $template_file = 'mustache_templates/departments.html';
    $template_contents = file_get_contents($template_file);
    echo $m->render($template_contents, $template_data);

    // Free resultset and close connection
    $result->free();
    $mysqli->close();
    ?>

### Mustache Template

mustache_templates/departments.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Departments</title>
        <link rel="stylesheet" href="site.css" type="text/css"/>
      </head>
      <body>
       <h1>Faculty of Arts &amp; Sciences</h1>
       <h2>Departments</h2>
    <ul>
    {{#departments}}
         <li>
           <a href="mustache-courses.php?department_code={{department_code}}">{{department_short}}</a>
         </li>
    {{/departments}}
    </ul>
      </body>
    </html>

## Mustache Courses

    <!DOCTYPE html>
    <html>
     <head>
      <title>Courses: {{department_name}}</title>
      <link rel="stylesheet" href="site.css" type="text/css"/>
     </head>
     <body>
    <h1>Faculty of Arts &amp; Sciences</h1>
    <p><a href="mustache-dept.php">Return to Department List</a></p>
    <h2>{{department_name}}</h2>
    <table cellspacing="0" cellpadding="0">
    {{#courses}}
    <tr>
    <td class="abbrev">{{course_group_long}} {{num_int}}{{num_char}}</td>
    <td class="long">
      <strong>{{title}}</strong>
      <br/>
      <span class="faculty">{{faculty_text}}</span>
      <p class="description">
        {{description}}
      </p>
    </td>
    </tr>
    {{/courses}}
    </table>
    </body>
    </html>

## Hello! Greeting, Improved

Without a "name", present the user a form. With a name, provide a greeting.

- fourth.php
- fourth.php?name=John%20Harvard

    <?php
          $name = $_GET["name"];
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Greeting Page</title>
      </head>
      <body>
        <?php
          if ($name) {
            echo("<h1>Hello, $name!</h1>");
          } else {
            echo('<h1><label for="input_name">Enter name:</label></h1>');
            echo('<form method="get">');
            echo('<input type="text" name="name" id="input_name"/>');
            echo('<br /><input type="submit" />');
            echo('<br /><input type="reset" />');
          }
        ?>
      </body>
    </html>

## Greeting, Improved

- greeting/index.php
- greeting/index.php?name=John+Harvard

Three files: one code; two templates

- index.php
- greeting.html
- form.html

### index.php

    <?php
    $name = $_GET["name"];

    // figure out which template is needed
    if ($name) {
      $template_file = 'greeting.html';
    } else {
      $template_file = 'form.html';
    }
    $template_contents = file_get_contents($template_file);
    $template_data['name'] = $name;

    // Process with Mustache Template
    include('lib/Mustache.php');
    $m = new Mustache;

    echo $m->render($template_contents, $template_data);

    ?>

### greeting.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Greeting Page for {{name}}</title>
      </head>
      <body>
          <h1>Hello, {{name}}!</h1>
      </body>
    </html>

### form.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Greeting Page</title>
      </head>
      <body>
          <h1><label for="input_name">Enter name:</label></h1>
          <form method="get">
          <input type="text" name="name" id="input_name"/>
          <br /><input type="submit" />
          <br /><input type="reset" />
      </body>
    </html>

Copyright © David Heitmeyer