PHP Code simplifier

Daeva

In Runtime
Messages
407
I was digging through some of my code earlier today and I found this script I wrote a while ago that makes creating multiple pages with the same look and feel a breeze. Here's the scenario:

I was working on a very large site at the time and it would take me a while to create the pages by hand every time typing the same lines of code at the top with just minor changes. Finally I got fed up and wrote a class that renders the top portion of an html page for you, allowing you to specify parameters like whether or not to use a css file, it's location, the page encoding, meta tag attributes, javascript files, etc...

Here is the class:
Code:
<?php

   /*
     Author: David Kyle
     Date: 07/16/2006
     
     Class pageHeader is an includeable class the will maintain the same look and feel across multiple pages.
     Including it at the beginning of your page will allow you to specify certain parameters to customize the rendering
     and look of your page.
     Defaults have been implemented to expedite the addition of new pages with minimal setup.
   */
   
   
   class pageHeader { // class declaration
     
     private $pageTitle; // html title attribute value
     private $pageEncoding; // html encoding attribute value
     private $stylesheet = false; // whether to use a stylesheet or not
     private $styleUrl;
     public $extraContent;
     private $metaKeywords;
     private $metaDescription;
     public $scripts;
     
     function __construct($title,$encoding) {
         $this->scripts = new jScripts();
         if (strlen($title) > 0) {
             $this->pageTitle = $title;
         } else {
             $this->pageTitle = "Untitled Document";
         } // end if/else
         if (strlen($encoding) > 0) {
             $this->pageEncoding = $encoding;
         } else {
             $this->pageEncoding = "utf-8";
         } // end if/else
     } // end no-argument constructor
     
     public function getEncoding() {
       return $this->pageEncoding;
     } // end function getEncoding
     
     public function getTitle() {
       return $this->pageTitle;
     } // end function getTitle
     
     public function hasStylesheet($hasStyle) {
       switch ($hasStyle) {
         case 0:
           $this->stylesheet = false;
           return;
         case 1:
           $this->stylesheet = true;
           return;
         default:
           return $this->stylesheet;
       } // end switch
     } // end function hasStylesheet
     public function setStyleUrl($url) {
       if (strlen($url) > 0) {
         $this->styleUrl = $url;
       } else {
         $this->hasStylesheet(0);
       } // end if/else
     } // end function setStyleUrl
     
     private function getStyle() {
       return $this->styleUrl;
     } // end function getStyle
     
     public function setMetaTags($description, $keywords) {
       $this->metaKeywords = $keywords;
       $this->metaDescription = $description;      
     } // end function setMetaTags
     
     public function setExtraContent($content) {
       $this->extraContent = $content;
     } // end function setExtraContent
     
     public function write() {
       echo "<?xml version=\"1.0\" encoding=\"".$this->getEncoding()."\"?>\n";
       echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
       echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-us\" lang=\"en-us\" dir=\"ltr\">\n";
       echo " <head>\n";
       echo "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$this->getEncoding()."\" />\n";
       if (strlen($this->metaKeywords) > 0) {
         echo "  <meta name=\"keywords\" content=\"".$this->metaKeywords."\" />\n";
       } // end if
       if (strlen($this->metaDescription) > 0) {
         echo "  <meta name=\"description\" content=\"".$this->metaDescription."\" />\n";
       } // end if
       echo "  <title>".$this->getTitle()."</title>\n";
       if ($this->hasStylesheet(-1) == true) {
         echo "  <link rel=\"stylesheet\" type=\"text/css\" href=\"".$this->getStyle()."\" />\n";
       } else {
       } // end if/else
       for ($i = 0; $i<count($this->scripts->item(-1)); $i++) {
         echo "  <script type=\"text/javascript\" src=\"".$this->scripts->item($i)."\"></script>\n";
       } // end if/else
       echo "  ".$this->extraContent . "\n";
       echo " </head>\n";
     } // end function write
   } // end class pageHeader
   
   class jScripts { // class that handles all javascripts on a page
   
     private $scripts;
   
     function __construct() {
         $this->scripts = array();
     } // end constructor
     
     public function add($src) {
         array_push($this->scripts,$src);  
     } // end function add
     
     public function item($index) {
         if ($index == -1) {
             return $this->scripts;
         } else {
             return $this->scripts[$index];
         } // end if/else
     } // end function item
     
    
   } // end class jScripts
?>
Then, you just include this file at the beginning of your php document. Here is an example of it's usage:
Code:
<?php
  include "includes/pageHeader.php";
  session_start();
  $pageTop = new pageHeader("Page title","utf-8"); // where utf-8 is the page encoding
  $pageTop->hasStyleSheet(true); // confirm stylesheet existence
  $pageTop->setStyleUrl("Themes/main.css"); // location of stylesheet
  $pageTop->scripts->add("main.js"); // add a javascript file
  $pageTop->scripts->add("ajax.js");
  $pageTop->write(); // output the header
?>
I just thought i'd pass this along. It helped me out a lot since I don't like to use IDE's or any code aids. I suppose if you're using an editor though this is kind of useless. Let me know if you have any questions or problems getting it to work I'll be more than happy to help you out. Maybe you'll find a better use for it than I did.

Just trying to get some conversation started in this Forum since most people are pretty inactive on the programming side.
 
Yeah I just started getting back into PHP after 1-2 years of inactivity, I had never touched on the OOP side of it until today since people always used frameworks and I never wanted to. Good to know there are still some web programmers out there on here, thanks for the script.
 
no problem, I didn't think anyone cared ;). I'm working on an updated version of it, if you want, I can let you know when it's finished.
 
I've done something like this before, and this is a great idea.

usually I write most of the things that create page layout in CSS so I don't need to put style in the page.

but for including Javascript and stuff like that that are a part of the page, I'll usually write this in a PHP file and then in the other documents/pages just write

<?php
include ('./formatting.php');
include ('./javascripts.php');

then continue the document here, perhaps at the bottom having

include ('./header.php');
 
I did an OOP automatic page rendering too, but I did it for the entire layout... Also personally never cared too much for meta data...
I like the script though... Can't wait to see what your updated version is going to look like...
 
I'll make it a CF special! It's almost developed but I still have a few bugs and exceptions to handle. It's going to have different rendering options to make the page valid against the w3 standards: html 4.0, xhtml 1.0 strict, or xhtml 1.0 transitional. So far, it also allows for you to format the output so it doesn't look generated and it will create clean html code. I'm commenting the crap out of it. The new javascript class allows you to either link a .js file or directly imbed javascript as well as the ability to exclude the javascript from the header, so you can easily insert it anywhere into the page you need it(like form validation function calls, or scripts for tracking page statistics for google, yahoo, etc...) :D
 
I did page tracking scripts as well... I just started on the new design for my site as well... Though I am not sure if I want to validate it or not... Not saying I can't code with validations, just not sure if I really want to add it or not... Definitely won't be doing metadata, as I said before never cared to much for it... On top of that, not sure if this is going to be the version I stick with, or if I am going to re-do it again later... I guess it depends on how the code unravels lol...

Curious question to you... When I did my page tracking I did it all through php... Would you say it is better to do them with Javascript or Php? or something else? Also which do you like better? Perl, Python, or Php?
 
For statistics purposes and for Search Engine Optimization, I do all of my tracking through Google Analytics. The sheer volume of information they provide is such a valuable resource, plus the information is automatically exported to a pdf and e-mail to me on a daily basis for all the sites I work on. This is a Godsend for all the sites I have to monitor!(not to mention it's free)

It shows you 500+ things about your visitors including (country, state, city or province of origin, browser, os, screen resolution, color depth, java capabilities, browser version, flash version, time on each page, bounce rates, time on your site total, langing page, not to mention a complete site overlay where you can view your site, and they overlay what percentage of visitors clicked on which links on which page, and which links are most popular. What percentage of your traffic came from search engines vs direct input, and what percentage of those users came from which countries and had what browser features) *pant* *pant*.

I love it :D

I would use php if I wanted to create a demographic based on this information and target ads or content towards certain users.

Of those three I prefer php. Although, my heart is with .NET. Don't get me wrong, I love the open source community, but I'm all about making my job easier, and microsoft makes life so simple, without taking all the work out of it. .NET puts everything at your fingertips.

For example, in php, to handle a user login, you have to create the database, hash the passwords, worry about permissions accross the site, restrict access to certain users on certain pages, and manage the sessions.

ASP.NET all you have to do is drag a create user control onto the page, then run it, it will create a SQL Server database for you, automatically create tables to manage different user roles, profiles, access restrictions, password hashing, password recovery, etc... and it manages the sessions for you.

I can do all of those things, but why should I have to do them EVERY time I want this functionality? This frees me to develop new things so I don't have to fuss with all of the trivial nonsense.

/End Rant

*EDIT: Which do you prefer?
**EDIT: PM's might be better suited for this kind of conversation, lest we get this thread closed for being off-topic
 
I have been using Google Adsense for some time... I haven't tried the Analytics yet though; does sound interesting and intriguing.

Personally I like Php as well... I touched on Perl and Python when I was about 13 or 14, after I learned the syntax, I didn't care to learn any more about it lol...

I understand the whole making time more useful scenario, and I wouldn't mind learning ASP, but the whole .Net stuff... Never liked it, I have tried using it before, but even still, it makes me feel like I don't have full control over my code...

Well if you would like to pm that works for me lol, but if you wouldn't mind, we could also chat in my forum as well... Besides I could use some input, and maybe a few suggestions on making my design for my forum, so to speak, clearer and cleaner... (http://newrealm.no-ip.info)
 
Ok, here is the latest revision. I still have a lot more work to do on it, so I guess you could say that it's in BETA.
To Start:
Code:
1.) Include the file
2.) Create a new object of the file ($obj = new className(arg1,arg2,etc...))
2.a) In this case, it requires the page title and character set (both required for validation)  Default options are implemented if left blank however.  These are "Untitled Page" for title and "utf-8" for character set/encoding
3.) Set the document type(One of xhtmlSt, xhtmlTr, html4).  Defaults to html4 if left blank.
4.) Add styles/scripts  (Both jScripts and style classes take three parameters, with the exception of jScripts which takes a 4th argument that allows you to skip it's output in the <head> tag).  These arguments are (Boolean(True/False): Whether or not you are linking to an external script/style, String: location of file to link to, String: Source code of script or style if you are not linking)
5.) Add meta tags (name,content)
6.) Echo the output
Listing 1: Example Usage(index.php)
Code:
<?php
include "includes/pageHeader.php";
session_start();
$myScript = "var myVar = 0;";
$myVar = new pageHeader("Testing","iso-8859-1");
$myVar->setDocType("xhtmlTr");
$myVar->addMeta("keywords","test,test2,test3");
$myVar->addMeta("description","My test site");
$myVar->addScript(true,"<?test.js","",true); // check the replacing of unsupported characters
$myVar->addScript(true,"myScript.js","",false); // won't be in header
$myVar->addScript(false,"","var myVar = 0;",true);
$myStyle = "body {
  margin: 0px;
  font-size: 12px;
}
";
$myVar->addStyle(true,"",$myStyle);
$myVar->addStyle(false,"main.css","");
echo $myVar->writePage();
echo " </body>\n";
echo "</html>";
?>
The rest is too long to post in this. :(
 
Back
Top Bottom