📖 PHP Modularization and Templating

PHP has many tools designed to modularize code to encourage the DRY (Don't Repeat Yourself) principle of coding. Strategic coding requires creating modularized code for parts that can be reused. Web pages contain common sections that can be easily duplicated. It is a good practice to find ways to reuse this code without rewriting it for each use. Functions are often used to create these code objects, but in the case of large text strings like you find in the head section of html pages, there are better tools in php to support writing, accessing and maintaining this code.

Modularization

Modularization is a process of creating functions to perform tasks that are repeated throughout an application. Functions are created once and stored in a central location where php scripts call the functions as they are needed.

Advantages
  • write once, test once, use often
  • smaller overall application size
  • consistency across an application
  • abstraction - easier to follow logic through function calls rather than linear code
Process
  • identify tasks that are repeated throughout the application
  • break into logical units
  • create functions
  • modify application to call functions instead of using linear code
Server Side Includes

Server Side Includes store information in a separate file and then include (or require) the file in the program script.

Format
<?php
require_once '/pathToFile/myincludefile.php';
/* ---- or ---- */
include_once '/pathToFile/myincludefile.php';

// where '/pathToFile/myincludefile.php' is the complete relative file path to the file you want to include in the script.
// require will issue an error and stop script execution if the file cannot be found.
// include issues a warning and continues to try to run the script.

/* _once is optional. 
If not present, the file will always be included at the spot where it is called.
If present, the file will be included only if it has not already been previously included or required. This prevents including duplicated code which can cause issues such as duplicate function names, etc. */
?>
Advantages
  • code is stored in one place for easier maintenance
  • increased security - information can be stored in a location that is not accessible from the internet (away from snooping eyes!)
  • once code is tested and working, can be reused in multiple PHP scripts
  • reduces duplication
  • consistent application between multiple scripts
Heredoc

Heredoc is useful for writing out large blocks of text. It involves creating a custom delimiter instead of using single or double quotes. It helps avoid issues with quotes inside of quotes and allows free use of php variables within the text.

The Heredoc begins with <<< followed by a delimiter of your choice. Delimiter can be anything. Convention is uppercase letters, i.e. <<<HERE

The Heredoc ends by repeating the delimiter in isolation on a line with only a terminating semi-colon(;). IE: HERE; Warning: There can be nothing else on the line with the terminating delimiter. Nothing. No margin, no spaces, no tabs, no characters of any kind.

Example
<?php
$myString = <<<HERE
<p>This is some 'text' to display on a page along with some $variable values.</p>
<p>I don't have to worry about single and double quotes such as in a 
<a href="http://www.google.com">Link to Google</a> or other html code.</p>
HERE;
echo $myString;
?>
Templating

Templating is a useful way of eliminating repeating code and improving the site consistency. There are many duplicate parts of pages that can be modularized into a template for a site then included using php. Since php is a html rendering language, it generates html on demand. The template file is created with the reusable elements of the site pages then included at the end of the page build process in php. The practice of using a template in this context is to have a standard template with the basic site html code in the template and include it with each of the page content files that are written for the site. See the example below.

Basic HTML Page Essential Elements

Save the code below as 2 separate files named header.php and footer.php. They will be included in every content page of the site to provide basic html structure elements.

<!-- Contents of header.php -->
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo $pageTitle; ?></title>

  </head>

  <body>
    <header>
      <h1>Form Processing</h1>
    </header>
    <nav>
      <a href="index.php">Home</a> | <a href="form.php">Order Form</a>
    </nav>

<!-- Contents of footer.php -->
    <footer>© BHC Web Dev</footer>
  </body>

</html>

Save both pages with the .php extension and the server will process the php script to include the templates with the specified text contained in the page-specific variables.

Sample PHP Page with Page-specific Content
<?php
$pageTitle = "My Page Title";
$number = 2;
include 'header.php';

echo <<<EOD
<h1>This is the Page Heading</h1>
<p>This is some 'text' to display on a page along with $number variables, as needed.</p>
<p>I don't have to worry about single and double quotes such as in a 
<a href="http://www.google.com">Link to Google</a> or other html code.</p>
EOD;

include 'footer.php'; 
?>

The script will process as follows. The page will include 'header.php'; file with the page title specified in the $pageTitle variable. Then load the page content and then finally include 'footer.php';. The output will be as shown below.

<!-- Contents of header.php -->
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>My Page Title</title>

  </head>

  <body>
  
<!-- Page Content -->
    <h1>This is the Page Heading</h1>
    <p>This is some 'text' to display on a page along with 2 variables, as needed.</p>
    <p>I don't have to worry about single and double quotes such as in a
      <a href="http://www.google.com">Link to Google</a> or other html code.</p>
	  
<!-- Contents of footer.php -->
    <footer>© BHC Web Dev</footer>
  </body>

</html>
Improved Page Templating

There's a better way of doing this. Instead of including the header before the page content, we want to move it after. This will allow for better flexibility for processing data and returning pages with desirable results. We really don't want to generate any HTML until after we are completely finished with the PHP processing. We can also benefit from combine the header.php and footer.php files together leaving us with only one template file to manage.

Begin by combining the header.php and footer.php into one file. We'll name this file something like template.php. Add a print statement in the middle of the file between the header part and the footer part that prints the value of a $pageContent variable.

<!-- Contents of template.php -->
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo $pageTitle; ?></title>

  </head>

  <body>
    <header>
      <h1>Form Processing</h1>
    </header>
    <nav>
      <a href="index.php">Home</a> | <a href="form.php">Order Form</a>
    </nav>
		
	<?php print $pageContent; ?>

    <footer>© BHC Web Dev</footer>
  </body>

</html>

Then assign all page content to the $pageContent variable when you are building the output of your PHP content page.

Improved PHP Page with Page-specific Content
<?php
// process page-specific content
$pageContent = <<<EOD
<h1>This is the Page Heading</h1>
<p>This is some 'text' to display on a page along with $number variables, as needed.</p>
<p>I don't have to worry about single and double quotes such as in a 
<a href="http://www.google.com">Link to Google</a> or other html code.</p>
EOD;
// include the code below on every php page to assemble the content
$pageTitle = "My Page Title";
include 'template.php'; 
?>

The script will process as follows. The page will process any data and build the page content assigning the page output to the $pageContent variable. With the page title specified in the $pageTitle variable, the page is ready to include 'template.php';. The page will be built using the page template as the main structure while including the page title and contents in the template. Any updates to the site can be done in one page while the page process can be the focus of any individual page. We are decoupling the page content generation from the page view.