الأسبوع 4 · الوحدة ٢ «متطلبات ومراحل إنتاج المشروع» (١) مرحلة تصميم صفحات الموقع: مراحل المشروع الثلاث، مخطط صفحات الموقع، وظيفة كل صفحة، صفحتا الترويسة والاتصال تُكتبان مرة وتُضمَّنان · 3 دروس
3
Write once, include everywhere
ICT Secondary 2 Term 1, Unit 2, Topic 1: pp. 29–39
GoalExplain why the banner, the links and the connection code are written once and included in every page.
New words
include · to pull the content of another file into a page at that placerepetition · writing the same code again and again in many filesbanner · the picture shown at the top of every pagemenu of links · the six links that let a visitor move between the pages
Explanation
Every page of the site starts with the same banner and the same six links, and every page that uses data needs the code that opens the database connection. You could copy all of it into all eight files, but that is heavy and risky: if you rename one link, you must find it in every file, and one forgotten copy leaves the site inconsistent. The better rule is to write each part once. The banner and the links go into header.php, the connection code goes into connection.php, and each page includes them at its start with one line. Change header.php once and all pages change. In PHP the line is include, which you will study later; for now remember the idea: write once, include everywhere.
include header.php: banner and links→include connection.php: open the database→the page’s own content
Worked examples
Way of working
Files to edit for one renamed link
copy the links into every page
8
write once in header.php
1
Count the work. Eight pages each contain the six links. Mona renames the link “Search” to “Find”. Without a header file, she edits eight pages. With one header file, she edits one file.
Html
1<?php include("header.php"); ?>
2<?php include("connection.php"); ?>
3<h2>Add a term</h2>
Output
The visitor sees: the banner and the links (from header.php), then the heading Add a term.
Here is how add_term.php starts. Each of the first two lines includes a helper file. The visitor sees the banner and links, then the heading. The connection file prints nothing when it works.
Class activity
List three things from a school notice board that appear on every notice (for example the school name and the date). Say how a header file would help if the school changed its name. Write your answer in three sentences.
Practice
1
What is repetition in code, and why is it a problem?
Writing the same code in many files; one change must be made many times and a forgotten copy causes mistakes.
2
Which two parts are written once and included in every page?
The banner with the links (header.php) and the connection code (connection.php).
3
You rename one link. How many files do you edit if the links are in header.php?
One, header.php.
4
Which part comes first at the start of add_term.php?
The included header, then the connection, then the page’s own content.