music
OSdata.com: programming text book 

OSdata.com

creating an object oriented website

summary

OSdata RSS
News Feed


OSdata blog RSS.

OSdata blog RSS - add to Bloglines
OSdata blog RSS - add to Google Reader.
OSdata blog RSS - add to My AOL
OSdata blog RSS - add to Newsgator.

    This section discusses how to create an object oriented website in PHP and SQL.

    Although there are snippets of actual working code, this section is not a step by step tutorial (those follow). This is intended to give you an understanding of the project and why Object Oriented Programming is the appropriate answer for this project and probably the appropriate answer for your projects as well.

license

    This is example code from OSdata, This Side of Sanity, and Twiddledom, released under Apache License 2.0.

    Copyright © 2012, 2013, 2014 Milo

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

previous page   next page
previous page
timer in JavaScript
  next page
translation
Google

creating an object oriented website

summary

    This section discusses how to create an object oriented website in PHP and SQL.

    If you have been following along, you will remember that we used the .htaccess and a custom php file to create virtual web pages. Any existing web pages already on our website are accessed and displayed normally. Any webpage that doesn’t exist is created by our custom php file. The example was extremely bare because it was concentrating on the mechanics of virtual pages.

    Now we are going to create some actual pages. I won’t go into all of the gory details. Instead I will present an overview that will serve as both a tutorial and as an introductory overview of upcoming articles that will go into all of the gory details.

system of web pages

    We are going to assume some large scale collection of stuff to present on a website. This could be the catalog of products or services that you sell.

    In the example case, we are going to compare the Dewey Decimal Classification and the Library of Congress Classification System.

    This gives us two different, but related, systems that have a tree-like hierarchy. You will want to organize your items (products, services, whatever) into tree structures, but you are likely to find that your real world things don’t fit neatly into one true tree to unite all trees. So, the ability to handle multiple, overlapping trees (as with our simple DDC and LOC example) is going to be useful in the real world.

    We are going to store a central set of data about possible web pages and two specialized sets of data for each of our knowledge oranganization systems.

    We are going to create a few root classes: visitor, site, page, and topic.

    And we are going to create a few controller classes that organize everything and make sure that the web pages get created.

    Our classes can be neatly divided into Model-View-Controller (MVC) and persistent data.

    NOTE: This summary explanation flies through a lot of material very quickly. I do not actually tell you how to work with SQL databases or how to write PHP object oriented code. That material will be covered in the subsequent detailed tutorials. For now, just relax and get a general idea of how we are putting everything together. Those of you who already know how to write SQL and OOP PHP may find this summary sufficient to set off some ideas for your own website.

    NOTE: At the time that this tutorial is being written, not all parts of the system have actually been built. This means no finished source code to examine (although that will be added as soon as it becomes stable). And this means that a visit to the web site (which is currently workign) will result in only a partial set of the described features (Dewey Decimal is working, but Library of Congress and the comparison still needs to be coded).

so, why use Object Oriented Programming?

    There is no doubt that Object Oriented Programming (OOP) is a bit more challenging than procedural programming and certainly takes more thought and time in the design phase.

    So, why go to all of that extra trouble?

    Because every programmer is limited to the programming that they can keep in their mind at one time. That limit varies from person to person, bt everyone has that limit.

    OOP allows for large scale systems to fit into the human brain — and therefore become something that a programmer can program. It is rare that procedural programming can scale to a large system. It happens, but it is rare.

scope of our project

    The scope of our example project is the sum of all human knowledge. Really!

    We will compare the Dewey Decimal Classification with the Library of Congress Classification System. Dewey Decimal is the most common system used in librares and the Library of Congress Classification System is the one used in the world’s largest library (in terms of size of total collection).

    Both systems catalogue all of human knowledge, as represented by all of the books, periodicals, scrolls, audio recordings, films, and other tangible recording media.

    Chances are that the website you are going to build has a much narrower scope. The products, services, topics, or stuff of your website will be more focused.

    I will start by presenting the three database tables that are actually used for this project. These tables are probably simpler than the ones that you need for your project, but the basic design ideas will be the same.

main database

    Our main data base includes a topic key, two versions of topic titles (short and long), a kind code, a Dewey key, and an LOC code.

    Remember, you want to modify this to match your own purposes, but this should give you the basic idea of the essential things to include.

    The structure is as follows:

NameTypeCollationAttributesNullDefaultKeyExtra
topickeybigint(20) UNSIGNEDNoNonePrimaryAUTO_INCREMENT
compacttopicvarchar(255)latin1_general_ci YesNULLUnique 
expandedtopicvarchar(255)latin1_general_ci YesNULL  
kindvarchar(255)latin1_general_ci YesTINDEX 
deweykeybigint(20) UNSIGNEDYesNULLINDEX 
lockkeybigint(20) UNSIGNEDYesNULLINDEX 

    The topickey is used to find our entries in the topics table.

    The compacttopic is used as the name for our web files. We will append .html to these names.

    The expandedtopic is a human readable version of the topic title.

    The kind is used to identify what kind of topic we are dealing with. This becomes especially useful when we start creating subclasses for a wide variety of spcial kinds of topics and/or web pages.

    The deweykey is used to find our entries in the dewey table.

    The lockey is used to find our entries in the loc table.

    And the following are a few sample entries in the actual existing topics table online.

topickeycompacttopicexpandedtopickinddeweykeylockey
1topicfinderTopic FinderRNULLNULL
2generalreferenceGeneral ReferenceM11
3philosophyandpsychologyPhilosophy and PsychologyM22
4religionReligionM32
9lawLawMNULL10
27deweydecimalclassificationDewey Decimal ClassificationSNULLNULL
28libraryofcongressclassificationsystemLibrary of Congress Classification SystemSNULLNULL
38puresciencePure ScienceT6NULL

dewey table

    And here is the structure of the dewey table:

NameTypeCollationAttributesNullDefaultKeyExtra
deweykeybigint(20) UNSIGNEDNoNonePrimaryAUTO_INCREMENT
deweydecimalnumbervarchar(255)latin1_general_ci YesNULLIndex 
deweydecimalnamevarchar(255)latin1_general_ci YesNULL  
topickeybigint(20) UNSIGNEDYesNULLIndex 
deweyparentbigint(20) UNSIGNEDYesNULLIndex 

    The deweykey identifies the entry in the dewey table.

    The deweydecimalnumber is exactly what it says.

    The deweydecimalname is the subject title.

    The topickey is the key for the corresponding item in the topics table: Note that we already have a problem, because some topics can legitimately map to more than one entry in the main table. We will resilve this problem in future coding lessons.

    The deweyparent is the topicskey in the topics table that is the one and only true parent of this particular entry. This is a key from a different table, not a direct key from this table. We can use the deweykey in the topics table to identify the entry back here in the dewey table. This indirection allows us to identify matching Library of Congress entries (the goal is to compare the two classification systems).

    And an example of a few sample entries:

deweykeydeweydecimalnumberdeweydecimalnametopickeydeweyparent
1000General works, Computer science and Information2727
2100Philosophy and psychology327
3200Religion427
4300Social sciences727
5400Language1527
6500Pure Science3827
7600Technology2127
8700Arts & recreation3927
9800Literature3927
10900History & geography4027

loc table

    The Library of Congress table is very similiar to the Dewey Decimal table.

    And here is the structure of the loc table:

NameTypeCollationAttributesNullDefaultKeyExtra
lockeybigint(20) UNSIGNEDNoNonePrimaryAUTO_INCREMENT
locnumbervarchar(255)latin1_general_ci YesNULLIndex 
locnamevarchar(255)latin1_general_ci YesNULL  
topickeybigint(20) UNSIGNEDYesNULLIndex 
locparentbigint(20) UNSIGNEDYesNULLIndex 

    The lockey identifies the entry in the loc table.

    The locnumber is exactly what it says. Note that the LOC system starts with letters, even though we are calling it a number.

    The locname is the subject title.

    The topickey is the key for the corresponding item in the topics table: Note that we already have a problem, because some topics can legitimately map to more than one entry in the main table. We will resilve this problem in future coding lessons.

    The locparent is the topicskey in the topics table that is the one and only true parent of this particular entry. This is a key from a different table, not a direct key from this table. We can use the lockey in the topics table to identify the entry back here in the loc table. This indirection allows us to identify matching Dewey Decimal entries (the goal is to compare the two classification systems).

    And an example of a few sample entries:

lockeylocnumberlocnametopickeylocparent
1AGeneral Works228
2BPhilosophy, Pyschology, Religion328
8HSocial Sciences728
10KLaw928
12MMusic1328
18TTechnology2128

code

    Again, this tutorial is an overview. I will only be presenting a few illustrative snippets of code and I will not actually be explaining how to write them (that’s all for subsequent tutorials).

    Sit back and relax and get a feel for how everything fits together before we dive into the mechanics of actually writing Object Oriented Programming.

overhead

    A little bit of overhead (discussed previously in virtual pages):

/***************/
/* Pre-Process */
/***************/

// include function files for this application
define("ROOT_PATH", '/home/twiddledom/public_html/');
require_once(ROOT_PATH . 'config.php');

/*************/
/* MAIN PAGE */
/*************/

initialization

    Now create our basic objects. In our simple example, we only have one of each major object. We will look at the classes after looking at the dispatcher.

/* INITIALIZATIONS */
$incomingurl = $_SERVER['REQUEST_URI'];

/* CREATE SITE OBJECT */
$siteobject = new SiteClass(1);

/* CREATE VISITOR OBJECT */
$visitorobject = new VisitorClass(1);

    The first line obtains a copy of the URL that was used to arrive at the current web page. That’s pretty much the same as it would occur in old fashioned procedural programming.

    The next two lines are real object oriented programming.

    We create a new site object from the SiteClass and a new visitor object the VisitorClass and store a reference to each in variables.

    During construction, each object is initialized to appropriate values for the current state of the system.

visitor object

    At the time of the writing of this tutorial I haven’t yet built the system for logging in and keeping track of visitors, so this class is almost empty.

    That makes this a better class to show to a newbie than a complete working class. Later I will reveal all of the complete working classes, but a little at a time so that you can follow along.

    For now, here is an almost empty (but real) class:

/****************/
/* CLASS        */
/* VisitorClass */
/****************/

class VisitorClass note 1
{

private $visitornumber; note 2
private $useragent;
private $browserlanguage;

/*************************/
/* CLASS: VisitorClass  */
/* FUNCTION: __construct */
/*************************/

protected function __construct($visitornumber) note 3
  {

    /* INPUT VARIABLES */
    $this->visitornumber = $visitornumber; note 4

    /* get visitor information */ note 5
    $this->useragent = $_SERVER['HTTP_USER_AGENT'];
    $this->browserlanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

  } /* END function __construct */

/*************************/
/* CLASS: VisitorClass  */
/* FUNCTION: __destruct */
/*************************/

  { note 6

    /* NOTHING HERE YET */

  } /* END function __destruct */

/*************************/
/* CLASS: VisitorClass  */
/* FUNCTION: __toString */
/*************************/

  { note 7

    return 'SiteClass object: visitor number: '.$visitornumber.' data: '.$this->useragent.' '.$this->browserlanguage;

  } /* END function __ toString */

} /* END VisitorClass */

    Note 1: We declare our VisitorClass.

    Note 2: We declare the private variables for the class. Each instance of the visitor object will have this set of internal data and the internal data is private so that no other object can directly access or modify the data. This prevents having to track down every function or procedure that might directly modify the state of a variable. All access and modification is handled by requests to the object and the object keeps track of what is allowed and when.

    Note 3: The construtor is automatically run whenever a new object iof this class is created. We declare this protected so that the classes that extend this class (subclasses) can freely access the base class version, but all outsiders (anything else, functions, other classes, just straight inline code) can’t modify or muck around with the internals of our objects.

    Note 4: This will change in the future, but I purposely put it here for the purposes of demo. In the future, we will have a better method to determine the unique visitor number (probably tied to the numbering system for our autohorized visitor/customer/employee/whatever database). This number has been determined by some external, unspecified code and is passed in at the time of the object creation.

    It will be very common for your objects to have input variables. These allow outside objects to create specific objects that meet specific needs. In our real example, you will soon see a snippet of our controller creating a topic object. A single web page might have many topics. The controller needs a way to assign a specific topic to each topic object. This is how it is done.

    Note 5: These are variables that the object can figure out on its own.

    Note 6: The destructor is automatically run whenever an object is deleted. At the moment this is empty. This is where we perform any required clean up, such as closing files, shutting down open connections, deleting child objects, final database updates, etc.

    Note 7: This is what gets printed out if the object is echoed as a string. We simply identify what kind of object (the class it belongs to), a unique identifying code (in this case, the visitor number), and the contents of the current internal variables.

dispatcher

    NOTE: Since this tutorial was written, some of the actions described in this section have been moved to a different class. This change isn’t significant to this tutorial, so this tutorial hasn’t been changed.

    Now comes the working code.

    Of particular interest is the dispatcher in the controller object. The dispatcher reads the URL that the website visitor has reached and then creates the corresponding objects needed to make that web page.

    When the topic object is created, we either initialize it with a number or a string.

    If the number is zero (a number that does not exist as a key in our database), then we create the topic directly from the visiting URL.

    Any other number is the topickey in the topic table. This is used to create new topic objects from keys stored in the database (such as the references already shown in the database structure.

    A string is the name of the topic. This is used to create a new topic object when we don’t have insider information from the database.

/* CREATE TOPIC OBJECT */
$topicobject = new TopicClass(0,'complete'); /* zero = determine from URL */

    And we create the page object from the main topic. We had type codes in our topics table. Those are used to determine (among other things) what kind of page object we need to generate.

    This illustrates an important point about Object Oriented Programming. There isn’t one monolithic class. There are a series of classes. The root or base class (PageClass) is the most basic and generic version, containing only those methods and data that will be used by every kind of page class.

    You will see in this snippet that we have different kinds of page classes. Each different page class inherits all of the methods and data of its parent or super classes, but adds additional methods and data for a more specific kind of page.

    This inheritance makes maintenance much easier. If we had to create a new class by copying and pasting common code, whenever we updated any piece of code, we’d have to track down every other location with that code and make the same change there. With two classes, that is double the work. Three clases, triple the work, four classes, quadruple the work. The work multiplies. And going through a lot of files scattered over several directories in a large scale project is a nightmare. Something, somewhere, is certain to be missed.

    By using inheritance, we make the change once in the base class (or another class in the scheme) and all of the children classes are immediately and automatcally updated.

/* CREATE PAGE OBJECT */
if ($topicobject->getattribute('kind', 'raw') == 'R' ) /* R is for root */
  $pageobject = new TopicFinderPageClass($topicobject);
elseif ($topicobject->getattribute('kind', 'raw') == 'M' ) /* M is for major category */
  $pageobject = new CategoryPageClass($topicobject);
elseif ($topicobject->getattribute('kind', 'raw') == 'S' ) /* S is for Knowledge Organization System */
  $pageobject = new SystemPageClass($topicobject);
elseif ($topicobject->getattribute('kind', 'raw') == 'I' ) /* I is for individual (human) */
  $pageobject = new PersonPageClass($topicobject);
else
  $pageobject = new PageClass($topicobject);

    If we don’t identify a particular kind of page, then we use our basic generic PageClass.

    And we render the page.

/* DRAWPAGE */
$pageobject->renderpage($topicobject);

render

    Rendering is also fairly straight-forward.

    There are a handful of basic operations that occur for a web page.

    The following is the base PageClass method for rendering a page. In this case we have only one topic for the page and we render the most generic version of web page.

/************************/
/* CLASS: PageClass     */
/* FUNCTION: renderpage */
/************************/

public function renderpage($topicobject)
  (

    $this->renderhead($pagetopicobject);

    $this->renderheader($pagetopicobject);

    $this->rendermainbodystart($pagetopicobject);
    $this->rendermainbody($pagetopicobject);
    $this->rendermainbodyend($pagetopicobject);

    $this->renderfooter($pagetopicobject);

  } /* END FUNCTION renderpage */

    The renderhead method renders the html head.

    The renderheader method renders beginning of the html body (things like the logo and nav bar).

    The three rendermainbodystart, rendermainbody, and rendermainbodyend methods renders the main section of the html body.

    The renderfooter method renders the footer of the html body.

    Again, we use inheritance and method override to extend and customize the generic behavior to match each individual web page’s needs.

conclusion

    That is the outline of how we are going to build the entire website.

    The following tutorials will go step by step through how we actually build a real version of a real web site. I am attempting to keep things simple enough that you can easily modify the sample code for almost any kind of website.

    As mentioned at the top of this tutorial, I will discuss the basics of PHP object oriented programming as we go along.

    NOTE: At the time that this tutorial is being written, not all parts of the system have actually been built. This means no finished source code to examine (although that will be added as soon as it becomes stable). And this means that a visit to the web site (which is currently workign) will result in only a partial set of the described features (Dewey Decimal is working, but Library of Congress and the comparison still needs to be coded).

return to source code lessons

return to Outrageous Coder
return to Source Code Examples

previous page   next page
previous page
timer in JavaScript
  next page
translation

contact
comments, suggestions, corrections, criticisms

because of ridiculous spam attacks,
contact through Twitter (@OutrageousCoder) will be more reliable than the contact form

please contact us

your name:
email address:
phone number:
message:

return to Outrageous Coder
return to source code lessons
return to table of contents
free downloadable college text book

license

    This is example code from OSdata, This Side of Sanity, and Twiddledom, released under Apache License 2.0.

    Copyright © 2012, 2013, 2014 Milo

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

previous page   next page
previous page
timer in JavaScript
  next page
translation

Google


Made with Macintosh

    This web site handcrafted on Macintosh computers using Tom Bender’s Tex-Edit Plus and served using FreeBSD .

Viewable With Any Browser


    †UNIX used as a generic term unless specifically used as a trademark (such as in the phrase “UNIX certified”). UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Ltd.

    Names and logos of various OSs are trademarks of their respective owners.

    Copyright © 2014 Milo

    Created: June 25, 2014

    Last Updated: June 25, 2014


return to table of contents
free downloadable college text book

previous page   next page
previous page
timer in JavaScript
  next page
translation