How to Create the Top of the Page with a PHP Template

By Steve Suehring, Janet Valade

The top of the page is one of the more complex sections for a PHP template system to handle. The top of a web page contains the document type declaration (DTD) along with links to the CSS and any JavaScript that will be used on the page. The top of the page also contains the title and other meta information about the page.

Aside from the information in the <head> section of a page, the top of the page that you’re using in this example also contains the menu shown here, with the links to other pages on the site.

image0.jpg

The class that you will create in this exercise has four methods for the top of the page, including both the <head> section and the menu. However, when using the class, you don’t want to have to call (or remember to call) all the various methods in the correct order to create the top section of the page.

All you care about is that you create a top section of the page. Therefore, there’s only one public method, called getTop. The getTop method is responsible for gathering all the bits to make the entire top of the page.

  1. Open classPage.php if it isn’t already open.

  2. Within classPage, just below the public $titleExtra = “; line, enter the following code:

        public function getTop() {
            $output = ";
            $output .= $this->_getDocType();
            $output .= $this->_getHtmlOpen();
            $output .= $this->_getHead();
            $output .= file_get_contents("pageTop.txt");
            return $output;
        } //end function getTop()
  3. Save classPage.php.

    The getTop() method creates a variable for the output. This gives flexibility to add to or remove from the variable as you need to. The method calls three additional methods, grabs some plain HTML from a file called pageTop.txt, and returns the output.

  4. Within classPage.php (open it if it isn’t already), below the getTop() method’s closing brace, enter the following code:

protected function _getDocType($doctype = "html5") {
if ($doctype == "html5") {
$dtd = "<!DOCTYPE html>";
}
return $dtd . "n";
}
protected function _getHtmlOpen($lang = "en-us") {
if ($lang == "en-us") {
$htmlopen = "<html lang="en">";