<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Metrol's Development Corner</title>
	<atom:link href="http://metrol.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://metrol.wordpress.com</link>
	<description>A little corner of the web for Metrol rants</description>
	<lastBuildDate>Mon, 18 Apr 2011 17:42:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='metrol.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Metrol's Development Corner</title>
		<link>http://metrol.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://metrol.wordpress.com/osd.xml" title="Metrol&#039;s Development Corner" />
	<atom:link rel='hub' href='http://metrol.wordpress.com/?pushpress=hub'/>
		<item>
		<title>PHP Looking at Python</title>
		<link>http://metrol.wordpress.com/2008/03/18/php-looking-at-python/</link>
		<comments>http://metrol.wordpress.com/2008/03/18/php-looking-at-python/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 17:15:15 +0000</pubDate>
		<dc:creator>Michael Collette</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[comparison]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://metrol.wordpress.com/?p=16</guid>
		<description><![CDATA[Compare and contrast PHP and Python in how they approach programming.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=16&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Have a look at any message board that is silly enough to actually mention PHP or Python in the title and you have all you need for a virtual battle for the “P” in <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" title="Wikipedia article about LAMP" target="_blank">LAMP</a>.  Not to be forgotten is Perl, but that one will have to wait for later.  Today&#8217;s post will attempt to look at <a href="http://www.python.org/" title="Official Python site" target="_blank">Python</a> from the eyes of a <a href="http://upload.wikimedia.org/wikipedia/en/a/aa/Model_with_extra_thick_glasses.jpg" target="_blank">PHP programmer</a>.  I will not promise an unbiased viewpoint, but I can tell you right up front that both languages fill a niche for getting certain jobs done quite nicely.  Both languages also have some really odd ball things to them&#8230; usually for very good reasons depending on how you feel about those reasons.</p>
<p>Although it sometimes feels like there&#8217;s a new programming language coming out from somebody every couple of weeks, I believe it is now fair to say that both PHP and Python are very well established platforms for development.  Both enjoy considerable corporate support, as well as very active user communities.  They also jump across the operating system divide reasonably well.<span id="more-16"></span></p>
<p>The following is not meant to be a full tutorial on the Python programming language for a PHP developer.  I would hope that it would make reading a full tutorial a good bit easier.  Python is a rich language with a wide variety of capabilities.  If I leave a few of the Python details out of the picture I just want you to know up front this is not meant to bolster PHP.</p>
<h1>Where They Came From</h1>
<p>Most PHP folks have already heard the story so many times as to cause eyes to roll when yet another site gets into the <a href="http://en.wikipedia.org/wiki/Php" title="Wikipedia article about PHP" target="_blank">history of their platform</a>.  Sorry folks, need to do it here again.  I&#8217;ll try to keep it short.</p>
<p>PHP started as a set of Perl scripts to solve some form processing issues on the author&#8217;s web site.  They were his Personal Home Page tools, and thus the acronym was born.  Over time the number of those functions increased to a point where PHP was becoming a full language itself.  Eventually the engine was moved to C and the Personal Home Page tools meaning was dropped.  Today PHP is no longer an acronym, just the name of the language.  At it&#8217;s core from its very earliest days PHP was a procedural language to get things done on the web quickly and easily.</p>
<p>At the time <a href="http://en.wikipedia.org/wiki/Perl" target="_blank" title="Wikipedia article about Perl">Perl</a> ruled the dynamic web site game.  For all the good or bad you can say about Perl, it was outpaced by the ease of use that PHP provided programmers.  When PHP got matched up to a MySQL database that&#8217;s when things really started to shine.  Put those two on a Linux machine running the Apache web server and the LAMP stack was born.  PHP didn&#8217;t really need any of the other parts, as it ran on other operating systems with different web servers and could talk to a wide variety of database engines.  Still, LAMP is where the success really took off.</p>
<p>Python <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" target="_blank" title="Wikipedia article about Python">started life a bit differently</a>.  Where PHP sort of became a programming language almost by accident, Python began life as a better way to develop a general purpose programming language.  Object oriented at it&#8217;s core, but still supporting procedural methodologies so it could be used for scripting as well as a scalable programming language.  It too was focused on simplifying the life of developers by taking care of memory management and removing extraneous syntax.</p>
<h1>How Different Are They</h1>
<p>Once you get past some of the definitions the languages use to describe certain aspects about themselves, there are more similarities than differences.  To be sure, there are differences, but many of the same programming structures you would do in PHP look very similar in Python.  You&#8217;ve got “if” statements, “while” loops, strings, integers, classes, objects, inheritance and enough tools in either language to carry over knowledge from one to another.</p>
<p>What is <a href="http://wiki.python.org/moin/BeginnersGuide/Overview" title="Beginners Guide to Python" target="_blank">notable about Python</a>, compared to most languages, is what it doesn&#8217;t have.  Mostly, a lot of the carry over syntax from C and <a href="http://www.perl.org/" title="Official Perl Website" target="_blank">Perl</a> that got stuffed into PHP.  If you&#8217;re making the leap into Python say goodbye to your good friend the semi-colon “;”.  In Python the end of a line is the end of the command, so there&#8217;s no need for them.  They can be used for compounding multiple statements on a single line, but that&#8217;s just sloppy no matter what language you&#8217;re talking about.</p>
<p>You can also say goodbye to those lovely <a href="http://en.wikipedia.org/wiki/Curly_bracket_programming_language" title="Curly bracket programming languages" target="_blank">curly brackets</a> “{ }” to define your “if” and “while” structures.  In Python you define a structure by spacing.  Here&#8217;s a quick look at some very basic PHP and Python code illustrating the difference.</p>
<pre>-----------------------------------
&lt;?php
$x = “Howdy”;
if ($x == “Howdy”) {
  print “Howdy back atcha!”;
  $x = “”;
}
?&gt;
-----------------------------------
#!/usr/env python
x = “Howdy”
if x == “Howdy”:
  print “Howdy back atcha”
  x = “”
-----------------------------------</pre>
<p>I&#8217;ve included the PHP tags and the &#8220;#!&#8221; so you know which language is which here.  In the Python example you&#8217;ll note that the “print” statement is indented following the “if”.  This isn&#8217;t just good style, it&#8217;s a requirement in Python.  Every command indented along with that “print” is considered a part of the “if” block.</p>
<p>Most comments I have seen out there by folks who don&#8217;t like Python <a href="http://www.secnetix.de/~olli/Python/block_indentation.hawk" title="Myths about Python indentation" target="_blank">point to this</a> single syntactic detail as a reason for their dislike.  The notion that using proper style as a part of the language&#8217;s syntax is just wrong in their eyes.  From Python&#8217;s perspective, any decent programmer is already going to be indenting their code in this fashion, so why not lose all that extra cruft and make it part of the syntax?  Furthermore, by getting rid of that extra junk there will likely be fewer syntax errors due to the missing brace or semi-colon.</p>
<p>Python makes a good point here.  I doubt there&#8217;s a single PHP developer alive who hasn&#8217;t been caught by a missing semi-colon, or improperly nested brackets.  In practice, I definitely don&#8217;t miss those semi-colons which aren&#8217;t much more than a legacy from C.  I do miss those curly brackets though.  Especially since my text editor is able to automatically show the matching brace when the cursor is near by.  With nothing but indentation defining code I find it a little more difficult to visually define a block.</p>
<p>Issues of style are highly subjective.  You could argue that Python&#8217;s layout looks more like a page layout made up of paragraphs.  Without the extra punctuation source code can look cleaner.  Even though Python essentially uses style to define blocks, there are still numerous ways for a programmer to obfuscate the code.  When it gets right down to it, the readability of the source code is still up to the programmer to follow the style guides the language encourages.</p>
<p>You should also notice the difference in the variable “x”.  There is no special character, like PHP&#8217;s “$”, to define a variable.  The variables do look a bit cleaner, but once again without some way of flagging an editor there&#8217;s no good way to highlight variables.  Another minor annoyance is that you can&#8217;t do something like:</p>
<pre>$name = “Bob”;
print “Howdy there $name”;</pre>
<p>You would instead have to do something like this in Python:</p>
<pre>name = “Bob”
print “Howdy there “ + name</pre>
<p>Hey, where is the “.” dot connector for strings?  Python uses “+” to concatenate strings.  This turns out to be a much smarter way of doing this.  By not using “.” for string concatenation Python can use that dot for accessing object methods.  As opposed to PHP using Perl&#8217;s nasty looking arrow thing “-&gt;”.  I&#8217;ll get into object model a bit later, as this is a huge part of what makes Python what it is.</p>
<h1>Lists, Dictionaries, and Tuples Oh My</h1>
<p>There are other notable syntax differences, but these are usually pretty straight forward to mentally convert over to.  One of the nastier stumbling blocks when reading about Python is trying to keep track of what a <a href="http://docs.python.org/tut/node5.html#SECTION005140000000000000000" title="Python Docs - Lists" target="_blank">List</a>, a <a href="http://docs.python.org/tut/node7.html#SECTION007500000000000000000" title="Python Docs - Dictionaries" target="_blank">Dictionary</a>, and a <a href="http://docs.python.org/tut/node7.html#SECTION007300000000000000000" title="Python Docs - Tuples" target="_blank">Tuple</a> are.  These are essentially overly fancy names for arrays.</p>
<h2>Lists and Objects</h2>
<p>The following is an example of an index array in PHP and a list in Python.</p>
<pre>-----------------------------------
&lt;?php
$z = array(“stuff”, “things”, “widgets”, “gizmos”);
print $z[2];
?&gt;
-----------------------------------
#!/usr/env python
z = [“stuff”, “things”, “widgets”, “gizmos”]
print z[2]
----------------------------------</pre>
<p>Both of these create a list of strings that can be accessed by an index value.  Where the two languages diverge is how you deal with this data.  Let&#8217;s start by adding a new element to each then sorting the data.</p>
<pre>-----------------------------------
&lt;?php
$z[] = “garbage”;
sort($z);
?&gt;
-----------------------------------
#!/usr/env python
z.append(“garbage”)
z.sort()
-----------------------------------</pre>
<p>This illustrates a fundamental difference in how these two languages view data.  In PHP, the variable $z is the container for the array in question.  Since $z actually contains this data, it would make sense that in order to do something to that data you would need to pass it on in to a function to process it.</p>
<p>This list of elements in Python is actually an object, with z acting as the pointer to that object.  An object carries with it the actions that can be performed on it via methods.  In this case, it makes sense that rather than passing z to a function you would instead access a List Object method to manipulate it.  In a really rough way, you can think of it like the following PHP class.</p>
<pre>&lt;?php
class ListObject
{
  $listData = array();

  public function __construct()
  {
    foreach (func_get_args() as $arg) {
      $this-&gt;listData[] = $arg;
    }
  }

  public function append($data)
  {
    $this-&gt;listData[] = $data;
  }

  public function sort()
  {
    sort($this-&gt;listData);
  }
}
?&gt;</pre>
<p>Again, this is a really rough way of looking at what Python is doing. When you created that list called z you were actually creating a new object. Like if you were to do the following in PHP.</p>
<pre>&lt;?php
$z = new ListObject(“stuff”, “things”, “widgets”, “gizmos”);
$z-&gt;append(“garbage”);
$z-&gt;sort();
?&gt;</pre>
<p>Everything in Python is considered an object.  When you create a list, dictionary, a string, etc., you are in actuality creating a built in Python object of that type.  This has provides for benefits that a Python developer can make good use of.</p>
<p>PHP has 75 functions to deal with handling arrays.  They all have to exist in the global namespace, so you can&#8217;t put together a user defined function using any of those names. Python doesn&#8217;t run into these kinds of <a href="http://docs.python.org/tut/node11.html#SECTION0011200000000000000000" title="More about Python namespace" target="_blank">namespace issues</a>.</p>
<p>You can actually extend Python&#8217;s built in types.  So, if you need a method to deal with a List that Python doesn&#8217;t have then you can easily add it in through inheritance.</p>
<p>Since Python&#8217;s built in types are run in C the methods are wicked quick.</p>
<p>Cleaner namespace, faster execution, extendability&#8230; what&#8217;s not to love?</p>
<p>For PHP, giving over the ability to override a built in function is a no go.  Not because the language couldn&#8217;t allow something like this, but it starts into issues with the integrity of the commands.  When you ask for a sort of the elements in an array you always know that you&#8217;re running the real sort function.  In Python things may not be that straight forward.</p>
<p>This is also not because PHP isn&#8217;t object oriented from the get go.  Even a language like Java, which is also very centered around the notion of objects, doesn&#8217;t allow overriding built in methods.  For some, Python&#8217;s flexibility in this regard is seen as a good thing, where others may regard this as a liability.</p>
<p>Not only are creating and filling lists different under the hood in Python, but getting data back out has some pretty cool features to it.  The first time I saw a setup like this was way back on Atari Basic (okay, I&#8217;m really showing my age here).  Python calls it “slicing”.  Here&#8217;s how that plays out:</p>
<pre>#!/usr/env python
print z[0]</pre>
<p>Nothing too special there.  That outputs “stuff”.  Now here&#8217;s a taste of the clever stuff.</p>
<pre>#!/usr/env python
print z[0:2]</pre>
<p>So that&#8217;s kind of odd.  What you get back from that is ['stuff', 'thing'].  This outputs a list, as denoted by the brackets, with the first 2 elements.  I&#8217;ll leave the full story about slices to a more complete Python tutorial, but this is one of those features that once you get acquainted with it you&#8217;ll be looking over the fence at Python&#8217;s yard in envy.  It also knocks out an entire stack of those array functions PHP relies upon.</p>
<p>I won&#8217;t be getting into it here, but strings are dealt with in a similar way.  Instead of substr() kinds of functions you use slicing to pull out portions of text.</p>
<h2>Dictionaries</h2>
<p>So if a list is sort of like an indexed array, what is a dictionary?  Pretty much an associative array.  You get to put items into this array using key/value pairs.</p>
<p>Just when you thought you would see the last of curly brackets “{ }” by jumping to Python, they come right back with dictionaries.  Where a list uses brackets to frame up the data list, curly brackets frame up dictionaries.</p>
<pre>-----------------------------------
&lt;?php
$z = array( “stuff” =&gt; 2,
            “things” =&gt; 42,
            “widgets” =&gt; 37,
            “gizmos” =&gt; 12 );
print $z[“stuff”];
?&gt;
-----------------------------------
#!/usr/env python
z = { “stuff”: 2,
      “things”: 42,
      “widgets”: 37,
      “gizmos”: 12 }
print z[“stuff”]
----------------------------------</pre>
<p>Like lists, dictionaries are an object type with a variety of methods for manipulating them. As you might well imagine, you deal with these a good bit differently than what you would expect from an associative array.</p>
<p>Rather than getting into the details of dictionaries, I would like to point out one advantage to this overall approach versus what PHP does.  Picture one such array in PHP that you have built up.  You then add a key/value pair where the key is an integer.  Wrap it in quotes all you like, PHP will take that and make it an index value even though what you wanted was an associative style key/value.</p>
<p>Python doesn&#8217;t suffer from this problem since a list and dictionary are independent objects.  In a dictionary, a key is always a key. I really think Python&#8217;s approach to explicitly separating these two kinds of grouped data is a huge benefit.</p>
<h2>Tuples</h2>
<p>Finishing off the stack of data types that hold multiple values we have the &#8220;tuple&#8221;.  Simple as I can put this, a tuple is a list that the values of can not be changed in place.  If you were to actually study up on Python you would most certainly be well versed in &#8220;mutable&#8221; and &#8220;immutable&#8221;.  Not getting into all of that here beyond saying that a tuple is immutable since it can&#8217;t be changed.</p>
<p>For example, when I sorted the list earlier that actually altered the list object in place.  A tuple can&#8217;t be altered in place, so you won&#8217;t be running a sort, or any other method that would alter it.  So why have tuples at all?  One reason for them is a degree of data integrity.  Since they can&#8217;t be altered, you know that when you pass a tuple around it retains it&#8217;s value.  More importantly, tuples can be used in places where lists can&#8217;t be.  Things like function calls and such.  In fact, you see something like a tuple all the time in PHP without thinking about it.</p>
<p>So lists have brackets &#8220;[ ]&#8220;, dictionaries have curly brackets &#8220;{ }&#8221;, and tuples have parenthesis &#8220;( )&#8221;.  Pretty much any time you see values in parenthesis you&#8217;ve got a Python tuple.</p>
<pre>-----------------------------------
&lt;?php
$z = array(“stuff”, “things”, “widgets”, “gizmos”);
print $z[2];
?&gt;
-----------------------------------
#!/usr/env python
z = (“stuff”, “things”, “widgets”, “gizmos”)
print z[2]
-----------------------------------</pre>
<p>I could go on for a while about the various syntax issues between the languages, and many very good books do just that.  Time to dive into more controversial stuff.</p>
<h1>Object Oriented Code</h1>
<p>Both of these languages now support object oriented design, thanks to PHP5.  Python has always had this in place, but it&#8217;s model is a bit different.  Python uses &#8220;class&#8221; to define objects, like PHP.  Unlike PHP, Python objects are pretty much wide open at all times.  There&#8217;s no <a href="http://docs.python.org/tut/node11.html#SECTION0011600000000000000000" title="Python Name Mangling" target="_blank">concept of &#8220;private&#8221;</a> or &#8220;protected&#8221; members or methods.  Any data member can be altered by any code accessing that class.  You can even dynamically assign new data members to a class without having to do so in the class itself.</p>
<p>You can simulate similar behavior with PHP&#8217;s <a href="http://us3.php.net/manual/en/language.oop5.overloading.php" title="PHP Object Overloading" target="_blank">__set and __get magic methods</a>.  With Python, this kind of dynamic assignment is built in to every class, whether you want it or not.</p>
<p>If that last sentence sounded a little biased, my apologies.  I was hoping it would sound very biased.</p>
<p>In my personal opinion a class should be a fixed blueprint used to define an object.  Python seems to see a class as just another means for wrapping data into a container with inheritance benefits.  Depending on how you view OOP design issues this may be a good or bad.  Even from a PHP perspective, which plays fast and loose with a number of design issues, Python&#8217;s approach may be a bit much in providing flexibility.</p>
<h2>Inheritance</h2>
<p>With PHP a class may inherit from exactly one parent.  That parent can in turn be inherited from another parent and on up through any number of generations.  Python can of course inherit from a parent, but it&#8217;s not limited to just one.  You can inherit numerous parent classes into a single class.</p>
<p>Languages that restrict inheritance to a single parent, like PHP, usually point to naming conflicts as the reason for the restriction.  Python deals with that by providing for a specific search order to how it looks for methods or members in the class tree.  For example:</p>
<pre>class MyClass(Parent1, Parent2, Parent3):
  pass # an empty statement</pre>
<p>Let&#8217;s say you have a method called doSomething() that is in one of those parent classes.  Python begins at the lowest level of the tree, then at each level goes from left to right looking for that method.  In the above example the search starts with Parent1, then to Parent 2, and so on.  If it isn&#8217;t found, on up the tree it goes and repeats.</p>
<p>The cool part about this kind of inheritance is that you can have a number of utility classes that can be inherited into a wide variety of classes.  Things like database handlers, file management, or text processing.  You can maximize the reuse of your code by just inheriting into the class you&#8217;re writing and away you go.</p>
<p>There&#8217;s a hidden cost here though.  Well, a number of them actually.  As restrictive as PHP is about inheritance, you always know there is going to be a linear path from the lowest child to the top of the class tree.  Tracking back is a relatively simple process.  Allowing multiple inheritance opens the door wide to creating a maze of class trees to climb through.</p>
<p>A more fundamental problem here is the notion of &#8220;IS-A&#8221; and &#8220;HAS-A&#8221; relationships.  This being a metaphor that developers can use to determine whether or not you should inherit from a class or use an object from that class.  By allowing inheritance from multiple parents this metaphor is an easy one to break, thus muddying up the waters of what is considered proper OO design.</p>
<p>Of course you don&#8217;t have to actually use multiple inheritance in Python.  You can structure your code as you see fit.  The problem with allowing this at all comes in when you need to work on or with someone else&#8217;s code.  Did that other person already merge an unrelated class into the tree you wish to inherit from?  How wide is that class tree you&#8217;re wanting to inherit from?  What kind of time is involved with hunting all of that down?</p>
<p>You can run through these arguments back and forth for a while.  You&#8217;ll certainly see this in mailing list threads as the &#8220;proper&#8221; way to handle OO design is debated.  How much importance you put on being able to control access and structure of your classes will be a determining factor in whether Python is right for you.  Java is on one extreme of defining exactly what a class is, and being able to lock it down.  Python over on the other extreme with a focus on flexibility.  PHP sits sort of between the two in this regard.</p>
<h2>Class and Methods</h2>
<p>Back in my earlier post discussing and introduction to Object Oriented Programming for PHP is made heavy use of a Product class.  Here I&#8217;ll present to you a similar class as it would appear in Python.</p>
<pre>class Product:
  model = ""
  description = ""

def __init__(self, index):
  self.pullFromDatabase()

def showProductSpecs(self, index):
  # Some clever display code

def displayProductPrice(self, index)
  # Clever price calculations returned

def pullFromDatabase(self, index)
  // Fancy database query would run here
  self.model = dataRow[“model”]
  self.description = dataRow[“description”]</pre>
<p>No curly brackets, and no semi-colons.  Instead of __construct() you now have __init__().  Both of those methods do the same thing, run when an object is created.  The other big difference you should have noticed is that &#8220;self&#8221; stuff in the argument list for every method.  This serves the very same purpose as &#8220;this-&gt;&#8221; does in PHP.  For some reason Python decided that just having that automatically pass into a method wasn&#8217;t explicit enough, so you have to pass it in through an argument.</p>
<p>The other, and probably more valid, reason for having to explicitly state &#8220;self&#8221; in the argument list is due to the fact that there&#8217;s really no such thing as a &#8220;static&#8221; method in Python.  When you define a method without &#8220;self&#8221;, it essentially becomes static since it doesn&#8217;t have access to an object instance that its class created.</p>
<p>In all fairness, the need for static classes in Python may be a moot point.  The main reason they&#8217;re handy in PHP is due to being able to group what are essentially procedural functions within the namespace of a class.  Python doesn&#8217;t have the namespace issues of PHP, so needing to group functions into a class is generally something you wouldn&#8217;t need to do.</p>
<p>Using a class to create an object is as simple as&#8230;</p>
<pre>p = Product(12)
print p.showProductSpecs(12</pre>
<p>Looks like I missed the &#8220;new&#8221; command.  If this were PHP you&#8217;d be right, but in Python there is no keyword for creating an object.  Everything is an object, so any time you see an assignment like the above happening an object is being assigned to a pointer.</p>
<p>Using an object is pretty much the same as with PHP, just a dot &#8220;.&#8221; instead of that dash arrow thing &#8220;-&gt;&#8221;.</p>
<h1>Namespace Handling</h1>
<p>A file containing functions, variables, and classes in Python is considered a &#8220;module&#8221;.  Importing a module from one file into another doesn&#8217;t (by default) just jump into the global namespace.  In fact, Python doesn&#8217;t even have a concept like a global namespace.  The scope of naming exists within a module at the top most level.</p>
<p>To briefly illustrate this point let&#8217;s pretend there is a function called doSomething() in the file &#8220;MyLibs.py&#8221;.  You want to utilize this function in the file you&#8217;re working on.  Here&#8217;s how this plays out in the code.</p>
<pre>import MyLibs
x = MyLibs.doSomething()</pre>
<p>There are a wide variety of variations on this theme.  You can change the import line to read &#8220;from MyLibs import *&#8221; and not have to specify &#8220;MyLibs&#8221; to call functions from it.  That line could be tweaked to only import the functions or classes you specifically want to utilize, or even give a specific name to how you access resources from that module.  I won&#8217;t bore you with all the details of dealing with modules.  These are some very powerful tools for bringing in code from other files without running into the kinds of namespace issues that PHP suffers from.</p>
<p>Python only has a about a dozen or so reserved keywords as a part of the core language.  As I mentioned earlier, PHP has 75 keywords just to deal with array functions.  Python allows a programmer to keep a fairly tight rein on the allowed scope of the namespace, where PHP throws tons of stuff into a global namespace that everything has to fit into.</p>
<p>Clearly Python has much better structure in handling namespace.  The only down side to this is that you really can&#8217;t define a global constant.  In PHP these can be pretty handy for dealing with site preferences and other pieces of information that need to cross scope boundaries.  I&#8217;ll grant you, that&#8217;s a very minor point, but one to be aware of if you&#8217;re looking to migrate code to Python from PHP.</p>
<h1>What Got Left Out?</h1>
<p>In short, lots!  I warned you up front this was not going to be an attempt at a full Python tutorial.  I didn&#8217;t get into string handling, or differences in &#8220;for&#8221; loops.  For the purposes of this post I believe much of that to be minor issues of syntax that a reasonably competent PHP developer would pick up on through a true tutorial. Those things are handled differently between the languages, but I don&#8217;t believe they do all that much to illustrate the conceptual differences.</p>
<p>Advanced Python topics like threads were left out since PHP doesn&#8217;t support them, and I wouldn&#8217;t have done the topic justice in this format.  This is the same reason why GUI development and/or network sockets weren&#8217;t discussed either.  There&#8217;s really good reasons why there are big fat books that cover the full scope of capabilities.  Both of these languages do a lot of stuff!</p>
<h1>Summary</h1>
<p>At the beginning of this post I talked about what drove these languages forward from their early days.  Even after all these years most PHP code is produced to do one basic task, get to that closing &lt;/html&gt; tag as quickly as possible.  Run through things as quickly as possible, then dump out of memory just as quickly to get ready for the next page.  This all obviously stems from the fact that PHP and web development go hand in hand.  This is a task that PHP was built for and does a fine job at.  Certainly PHP is capable of more than that, but I would venture to guess that PHP use away from the web is fairly limited.</p>
<p>Python is a general purpose platform, that can also be used for web development.  You could use it to script web pages, or even program the web server itself.  It&#8217;s proven itself as a fine GUI development platform with a wide variety of supported widget sets that can run on multiple platforms.  It integrates well with Java, and can make use of C libraries.  Anything from a simple shell script to an advanced multi-threaded application can make good use of Python.</p>
<p>Each of these languages have strengths and weaknesses in their approach to solving the universal problem of how to tell these stupid machines what to do.  Ultimately it&#8217;s up to you to determine which of these solutions best fits the problems that confront you.</p>
<p>If you are already knowledgeable in one of these two languages I would recommend the following.</p>
<ul>
<li>Listen to the supporters of each.  They can provide valuable insight into why these platforms do things the way they do.</li>
<li>Ignore suggestions pointing you to use this language or that.  Always keep in mind that humans have a basic need to feel justified in their decisions.  Getting others to agree with their world view helps to do that for them, but most likely will do little for you.</li>
<li>Focus on the languages that are getting talked about the most, and where actual applications are coming out of.  If certain languages are getting little attention there&#8217;s probably a good reason why.</li>
<li>Get knowledgeable about C, C++, Perl and Java.  Both PHP and Python derive quite a bit from these languages, even if what they got out of one or the other was to not implement something.</li>
</ul>
<p>Hopefully I&#8217;ve provided a reasonable comparison of these development platforms to you.  Leave a comment below and let me know what you think.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/metrol.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/metrol.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metrol.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metrol.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metrol.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metrol.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metrol.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metrol.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metrol.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metrol.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=16&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metrol.wordpress.com/2008/03/18/php-looking-at-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a26c380e3f4214e0f4e501b5a1dfa5ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">metrol</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP &#8211; Database Creating Objects</title>
		<link>http://metrol.wordpress.com/2008/03/13/php-database-creating-objects/</link>
		<comments>http://metrol.wordpress.com/2008/03/13/php-database-creating-objects/#comments</comments>
		<pubDate>Fri, 14 Mar 2008 00:29:26 +0000</pubDate>
		<dc:creator>Michael Collette</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://metrol.wordpress.com/?p=14</guid>
		<description><![CDATA[Building on prior posts, I explain how to use the information in a database to define the data structure of an object.  In so doing, this cleans up quite a lot of code and provides a better understanding of Object Oriented design.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=14&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Various content frameworks, such as <a href="http://www.djangoproject.com/" title="Django Official Project Site" target="_blank">Django</a> or <a href="http://www.rubyonrails.org/" title="Ruby on Rails Official Site" target="_blank">Rails</a>, allow a developer to define the data for the objects they use within the code.  From there they then handle creating the database structure on the fly.  This frees the developer from having to deal with database structure or most <a href="http://en.wikipedia.org/wiki/Sql" target="_blank">SQL</a>.  For myself, I have a lot of trouble thinking in those terms.  My thought process involves putting the data structure together on the database, then wrapping my code around that.</p>
<p>Building on my previous article about abstracting your database inserts and my little introduction to Object Oriented design, I would now like to put these two together for you.  While I&#8217;m at it, let&#8217;s see what we can do about pushing many of your data requests to your database into the background by having the table structure define your objects.</p>
<p>Fair warning, not much of what I&#8217;m about to get into makes sense without referencing my other two articles.  If you&#8217;re already comfortable with Object Oriented development you can certainly skip that article (though your comments would be appreciated there).<span id="more-14"></span></p>
<h1>Refresher</h1>
<p>In my <a href="/2008/03/08/php-from-procedural-to-object-oriented/" title="PHP - From Procedural to Object Oriented">Object Oriented post</a> I mentioned how doing things in this manner would save you some serious coding time.  It does this by getting you into thinking about how to best group similar bits of data and actions then share them through the rest of your code through inheritance.  What does this isn&#8217;t so much the structure of the code itself, but how the developer (that&#8217;d be you) approaches the problems they face.</p>
<p>My <a href="/2008/03/08/a-different-kind-of-db-abstraction/" title="A Different Kind of Database Abstraction">next post</a> got into the notion of utilizing the structure of your data in the database to do something intelligent with it.  In that case I showed how you could get a better handle on putting stuff into the database in a way that was both easier and provided for better integrity of that data.</p>
<p>Building on both of these concepts I intend to show you how we can take the data structure of your database to help define a wide variety of objects using just a wee bit of inheritance.</p>
<h1>Building The DatabaseObject Class</h1>
<p>I really need to learn how to come up with cooler names.  Even though it&#8217;s got a boring name it should provide us with something descriptive as we move along.  So let&#8217;s get together the beginnings of this.</p>
<pre>class DatabaseObject
{
  private $objectData = array();
  private $fieldList = array();
  private $primaryIndex = "";
  private $indexValue = 0;
  protected $dbPtr = FALSE;
  protected $databaseTable = "";

  public function __construct($id=0)
  {
    $this-&gt;dbPtr = fancyDatabaseConnector();
    $this-&gt;indexValue = intval($id);
  }
}</pre>
<p>Not much to it at this point.  We&#8217;ve got a couple of arrays, some strings, and an integer for our data members.  A simple constructor that passes an integer value along to the $indexValue member.  So, let&#8217;s get into what all this is supposed to do.</p>
<p>The $objectData array will keep all the data for an object stored in an associative array.  You know, like the one you get from running a <a href="http://us3.php.net/manual/en/function.mysql-fetch-assoc.php" title="PHP Manual - mysql_fetch_assoc function" target="_blank">mysql_fetch_assoc()</a> function.  The field names will act as the key, with what is either in, or needs to go into, the database as the value.  Needs to go into?  Oh yeah, we can also use this to update the database.  We&#8217;ll get there.</p>
<p>If you recall from my <a href="http://metrol.wordpress.com/2008/03/08/a-different-kind-of-db-abstraction/" title="A Different Kind of Database Abstraction" target="_blank">database abstraction post</a>, I used $fieldList as a place to store information about the field in question with a simplified subset of types.  In that earlier post that information was forgotten, but now that we&#8217;re in Objectville we can not only remeber this information, but use it.</p>
<p>The $primaryIndex will be the name of the field that stores&#8230; wait for it&#8230;. the primary index!  We&#8217;ll assign that when we go to populate the $fieldList array.  On a very related note, the $indexValue will be the, lacking a better way to say this, the value of the primary index.  Pretty simple stuff huh?</p>
<p>The constructor starts by calling out to a database connection function.  I didn&#8217;t want to get bogged down in connection details or the error handling that you &#8220;should&#8221; have in there.  For what I&#8217;m talking about here, just know you&#8217;ve got a database resource sitting in the $dbPtr member.</p>
<p>Last in our data member parade is the $databaseTable.  Kind of weird that it&#8217;s blank, and it has a different permission set.  I&#8217;m going to let the child class deal with that one, but I need it at least defined here for methods that will be running here.</p>
<h1>Getting The Data</h1>
<p>At this point we can&#8217;t get any data out of the database no matter how many fancy methods we toss in there.  We don&#8217;t know which table to get that data from!  Sounds like before we go any further we&#8217;ll at least need the skeleton of a child class.</p>
<pre>class Product extends DatabaseObject
{
  protected $databaseTable = "Products";

  public function __construct($id=0)
  {
    parent::__construct( intval($id) );
  }
}</pre>
<p>Yes, our good friend the Product class has returned to us from the <a href="/2008/03/08/php-from-procedural-to-object-oriented/" title="PHP - From Procedural to Object Oriented" target="_blank">OO tutorial post</a>.  This time he&#8217;s not the top of the tree, just a child of DatabaseObject.  To make sure the parent class gets passed the index value an explicit call is made to the parent&#8217;s constructor.</p>
<p>Getting back to the DatabaseObject class, let&#8217;s get a little pulling action going on from the database.</p>
<pre>class DatabaseObject
{
  private $objectData = array();
  private $fieldList = array();
  private $primaryIndex = "";
  private $indexValue = 0;
  protected $dbPtr = FALSE;
  protected $databaseTable = "";

  public function __construct($id=0)
  {
    $this-&gt;dbPtr = fancyDatabaseConnector();
    $this-&gt;indexValue = intval($id);
    $this-&gt;pullFromDatabase()
  }

  public function getValue($field) {
    if ( array_key_exists($field, $this-&gt;objectData) ) {
      return $this-&gt;objectData[$field];
    } else {
      return FALSE;
    }
  }

  private function pullFromDatabase()
  {
    if ( !$this-&gt;indexValue
         OR !$this-&gt;primaryIndex
         OR !$this-&gt;databaseTable) {
      return FALSE;
    }
    $id = $this-&gt;indexValue;
    $idFld = $this-&gt;primaryIndex;
    $table = $this-&gt;table;

    $query = "SELECT * FROM ".$table." WHERE ".$idFld." = ".$id;
    $queryResource = mysql_query($query, $dbPtr);
    $this-&gt;objectData = mysql_fetch_assoc($queryResource);
  }
}</pre>
<p>This still isn&#8217;t quite ready to run.  It seemed like a good stopping point to explain what has happened, and to illustrate one of the nifty little aspects of dealing with an object.</p>
<p>Once the object is constructed it then runs the pullFromDatabase() method.  Within that method if anything we&#8217;re going to need is missing it doesn&#8217;t run.  Sure, we&#8217;ve got the $indexValue and the $databaseTable from the child class, but we still haven&#8217;t hunted down the $primaryIndex yet.  I&#8217;ll be getting to that bit shortly.</p>
<p>I would like you to notice at this point something about the structure of pullFromDatabase().  There are no arguments being passed in.  Everything that method needs to know to run is sitting in those data members.  It also doesn&#8217;t return a value, since it directly assigns what it has pulled back from the database to this objects $objectData.  For you folks still working through getting out of procedural land, this is a pretty good example of how sharing data within an object class works out.  Due to this, methods aren&#8217;t limited to just arguments in and a single value out <a href="http://us3.php.net/manual/en/language.functions.php" target="_blank" title="PHP Manual - Functions">like a function</a> out there in global namespace land.</p>
<p>Since we&#8217;re putting all of this data into a private data member, $objectData, not even an inherited class can get to this information directly.  This is where the accessor method getValue() comes into a play. The additional advantage to this, outside of controlling how the data is passed around, is that now you can also handle what happens if a child class asks for a field that doesn&#8217;t exist.</p>
<p>As I said, this isn&#8217;t ready to roll yet.  The code to figure out the primary index hasn&#8217;t been put into place yet.  If you look at the line that assigns a value to the string $query it should be readily apparent that this is fairly important.  Now this class starts to get a bit longer, as it&#8217;s time to convert that old nasty dbFields() function into a slick method worked into this class.</p>
<pre>class DatabaseObject
{
  private $objectData = array();
  private $fieldList = array();
  private $primaryIndex = "";
  private $indexValue = 0;
  protected $dbPtr = FALSE;
  protected $databaseTable = "";

  public function __construct($id=0)
  {
    $this-&gt;dbPtr = fancyDatabaseConnector();
    $this-&gt;indexValue = intval($id);
    $this-&gt;dbFields_mysql();
    $this-&gt;pullFromDatabase()
  }

  public function getValue($field)
  {
    if ( array_key_exists($field, $this-&gt;objectData) ) {
      return $this-&gt;objectData[$field];
    } else {
      return FALSE;
    }
  }

  public function setValue($field, $value)
  {
    if ( !array_key_exists($field, $this-&gt;fieldList) ) {
      return FALSE;
    }
    $this-&gt;objectData[$field] = $value;
  }

  private function pullFromDatabase()
  {
    if ( !$this-&gt;indexValue
         OR !$this-&gt;primaryIndex
         OR !$this-&gt;databaseTable) {
      return FALSE;
    }
    $id = $this-&gt;indexValue;
    $idFld = $this-&gt;primaryIndex;
    $table = $this-&gt;table;

    $query = "SELECT * FROM ".$table." WHERE ".$idFld." = ".$id;
    $queryResource = mysql_query($query, $dbPtr);
    $this-&gt;objectData = mysql_fetch_assoc($queryResource);
  }

  private function dbFields_mysql()
  {
    // A translation array used to convert a specific MySQL data type to
    // a generic datatype used within this class.
    $dataTypes  = array("tinyint"   =&gt; "integer", "smallint" =&gt; "integer",
                        "mediumint" =&gt; "integer", "int"      =&gt; "integer",
                        "bigint"    =&gt; "integer",
                        "float"     =&gt; "float",   "decimal"  =&gt; "float",
                        "double"    =&gt; "float",
                        "varchar"   =&gt; "string",  "text"     =&gt; "string",
                        "char"      =&gt; "string",
                        "datetime"  =&gt; "date",    "date"     =&gt; "date",
                        "time"      =&gt; "date");

    // Go out and hunt down all that field information
    $query = "SHOW COLUMNS FROM ".$this-&gt;databaseTable;
    $queryResource = mysql_query($query, $this-&gt;dbPtr);

    // Run through it all and fill in the fieldList and fieldIndex vars
    while ( $row = mysql_fetch_assoc($queryResource) ) {
      $field = $row["Field"];
      $prop  = $row["Type"];
      $key   = $row["Key"];

      // Look for a value stored in parenthesis
      $sizeStart  = strpos($prop, "(") + 1;
      $sizeLength = strpos($prop, ")") - $sizeStart;

      if ($sizeStart &gt; 1) {  // We have a parenthesis
        $type = substr($prop, 0, $sizeStart - 1);
        $size = substr($prop, $sizeStart, $sizeLength);
      } else {               // No parenthesis, so set the size to zero
        $type = $prop;
        $size = 0;
      }

      // Look for a space in the Type, as that is used to specify unsigned
      // or some other type of attribute for this field.
      if ( strpos($prop, " ") ) {
        $attrib = substr($prop, strpos($prop, " ") + 1);
      } else {
        $attrib = FALSE;
      }

      // Assign the generic data type as the type we'll be storing in the
      // returned array.
      if ( array_key_exists($type, $dataTypes) ) {
        $type = $dataTypes[$type];  // Assign a generic data type
      }

      // Assign what we've discoverd to the fieldList array
      if ($key == "PRI") {
        $this-&gt;primaryIndex = $field;
      } else {
        $this-&gt;fieldList[$field]["type"]   = $type;
        $this-&gt;fieldList[$field]["size"]   = $size;
        $this-&gt;fieldList[$field]["attrib"] = $attrib;
      }
    }
  }
}</pre>
<p>The first thing to notice here is that there is now a new call in the constructor to the dbFields_mysql() method.  All that was needed to convert this from a procedural style function was a to add a few &#8220;$this-&gt;&#8221; references to the data members, and get rid of having to declare those variables at the top of the method.  There is also a new assignment for the $primaryIndex data member, which is what we&#8217;re really needing at the moment.  The pullFromDatabase() method now has all the information it will need to run.</p>
<p>I&#8217;ve also snuck in another little method you can use to change the data within that private $objectData.  The setValue() method allows an inherited class a controlled means for altering the data.</p>
<p>As setValue() presently exists it will work, but this method is hardly complete.  At this point it at least verifies that a field exists before allowing a value to be assigned.  Thing is, thanks to the dbFields_mysql method we also know what are the allowable values for each and every field.  At this point I&#8217;ve excluded that error checking for the sake of keeping this sort of brief.  Essentially you could work up a simple switch/case handler like in the dbUpdate() function from <a href="/2008/03/08/a-different-kind-of-db-abstraction/" title="A Different Kind of Database Abstraction" target="_blank">my earlier post</a>.</p>
<p>In a language like <a href="http://www.java.com/en/about/" title="About Java" target="_blank">Java</a> where type safety is integral the JVM handles making sure that only a string can be assigned to a string, or a number to an integer.  Here the setValue() method can be used to implement some type safety into your inherited classes, with the additional ability of insuring that string lengths and numeric values are all within bounds before storing them.</p>
<h1>Putting It To Use</h1>
<p>Let&#8217;s bring back the child class for just a moment here.</p>
<pre>class Product extends DatabaseObject
{
  protected $databaseTable = "Products";

  public function __construct($id=0)
  {
    parent::__construct( intval($id) );
  }
}</pre>
<p>Thanks to inheritance, this is now a fully database enabled object.  When you pass in an index all the fields are filled in from the database and are ready to use.  So let&#8217;s see it in action:</p>
<pre>$product = new Product(12);

print $product-&gt;getValue("model");
print $product-&gt;getValue("description");
$product-&gt;setValue("price", 12.32);</pre>
<p>That&#8217;s pretty much it.  No SQL to write.  It all just happens since the DatabaseObject class handles all of that.  Just creating the object makes all of the data readily available to us.  We can even change the data in a controlled way.  Well, we&#8217;re still missing one part of this over all puzzle, and that&#8217;s writing changes back to the database.  Again going back to my previous post about database abstraction, we have all the data sitting in an array that just happens to be in the exact format the dbUpdate() function is expecting to get in.</p>
<p>The correct way to do this would be to also convert that dbUpdate() function into a method for this class.  At this point I would hope that I have provided enough information on doing this so I&#8217;m not going to put that code in here for you. Let&#8217;s just call it a little bit of homework.</p>
<p>What I will mention here is a little publicly available  wrapper method to call your dbUpdate() method.</p>
<pre>private function dbUpdate_mysql()
{
  // Converted copy of that global function mentioned earlier
}

public function commitChanges()
{
  $id = this-&gt;dbUpdate_mysql();
  return $id;
}</pre>
<p>Now when you&#8217;re actually using that Product object you can send those updates to the database with just a simple:</p>
<pre>$product-&gt;commitChanges();</pre>
<p>You may be asking yourself, or at least I hope you would, why not just make dbUpdate() public and call it directly?  Isn&#8217;t it sort of a wast to call one method that doesn&#8217;t do anything but call another one?  Normally it would be wasteful, but in this case the cost is worth it.  By running your update requests through commitChanges() you can point to any dbUpdate routine.  In this case we&#8217;re using MySQL.  You may need to convert your application to use some other database backend at some point due to any one of a variety of reasons.  Don&#8217;t let yourself get locked in to just one kind of database call.</p>
<p>Perfect database abstraction is a myth.  It&#8217;s the holy grail of developers to have this one perfect suite of code that is able to talk to any database with the flip of a switch.  Like the grail, it is often seen just around the corner, but never actually acquired.  The truth of the matter is that often enough you&#8217;ll need a feature one engine provides but another doesn&#8217;t.  The only way to correct this is to be able to code directly to that engine.  By abstracting which set of methods are used to do the database transactions you&#8217;ve given yourself a way to update which functions are being talked to, without having to go out and alter every line of code that needs something from the database.</p>
<p>The commitChanges() method could just as readily called dbupdate_postgre(), or perhaps worked in some logic to select which method to call based on the type of database used.</p>
<h1>What&#8217;s Left For You To Do</h1>
<p>I&#8217;ve left a lot of gaps in that object to get to this point in the post.  Like my other posts, and what seems to be a recurring theme here, I&#8217;m not providing you copy and paste kind of stuff for your code.  That&#8217;s what <a href="http://pear.php.net/" title="PHP Extension and Application Repository" target="_blank">PEAR</a> is for.  Here my point is to show you what is hopefully a new and useful concept that you can take with you into your own development.  With that being said, here&#8217;s a list of items you should complete in order to make this class into something that you would use in production.</p>
<ol>
<li>Proper error handling for your database connection.</li>
<li>Data validation in the setValue() method.</li>
<li>Properly convert dbUpdate() into a method using data members rather than arguments.</li>
<li>Fully abstract the calls to the database to avoid engine specific calls.</li>
</ol>
<p>It doesn&#8217;t stop there.  You could work in little utility functions like date conversion to and from a database format and a unix date integer for use in the date() function.  Whatever else you can dream up for moving as much of the database handling into the background so you can focus on the logic of how you use that data in the foreground.</p>
<h1>Different Kinds Of Objects</h1>
<p>Let&#8217;s just say that you&#8217;ve put together a reasonably complete and production ready version of this DatabaseObject.  So far I&#8217;ve shown how you can use that to create a Product class that immediately has database reading and writing with all the data members in place ready to use.  Certainly there are many more kinds of objects out there that a database is going to hold.  Stuff like accessories, options, shopping cart data, and everything else that goes into completing a site.  If you&#8217;ve created the tables in the database with all the appropriate fields, you just keep extending from that DatabaseObject class.</p>
<pre>class Accessory extends DatabaseObject
{
  protected $databaseTable = "Accessory";

  public function __construct($id=0)
  {
    parent::__construct( intval($id) );
  }
}

class Option extends DatabaseObject
{
  protected $databaseTable = "Options";

  public function __construct($id=0)
  {
    parent::__construct( intval($id) );
  }
}</pre>
<p>Every new class your create from DatabaseObject gets all the basic features that your Product object got.</p>
<h1>Many Objects</h1>
<p>So far I&#8217;ve shown what I believe to be a pretty reasonable way to deal with individual database records.  This class is built around the notion of one record at a time as an object.  You can pull that information in and update it one at a time.  So what happens when you need to deal with 100 records at once?  Like a list of those products, or showing all the accessories available for a product.</p>
<p>The obvious answer to this is to just create a bunch of those Product objects.  It may be obvious, but not ideal.</p>
<pre>$indexList = array(12, 32, 14, 1, 87, 23);
foreach ($indexList as $index) {
  $prodObj[] = new Product($index);
}</pre>
<p>A quick example of creating 6 Product objects each loaded up with all the data associated with each index value.  The reason this isn&#8217;t an ideal solution is that you had to make 6 seperate database calls.  Imagine you needed to get a list of 100 products for 50 people all asking for them at the same time.  This approach just doesn&#8217;t scale well, especially considering how many different tables are already being needed to get together something presentable.  Usually the biggest bottleneck of a dynamic site is getting information out of the database.  We want to be as efficient there as possible for the biggest performance gains.</p>
<p>This is heading us down the road to something called an &#8220;aggregate class&#8221;.  Yet another big fancy phrase that means something pretty simple.  It&#8217;s just a class that has objects as data members.  In other words, and object that holds other objects.  For what I personally do to deal with this issue is create what I call a <i>list class</i>.  This probably has a fancier name than I&#8217;m aware of, so you can leave a comment if you know of such a thing.</p>
<p>In a list class I create empty DatabaseObjects then pull in a multi-row result directly from the database engine to fill them in.  Notice how in the DatabaseObject class the $index argument isn&#8217;t required?  In the pullFromDatabase() method I don&#8217;t try to get anything from the database unless I have an $index value.  Also note that in the setValue() method I check in the $fieldList array rather than the array holding results to determine if the field is valid.  These are all little hooks to allow a list class to do all the data filling.</p>
<p>Creating a list class is something I&#8217;ll leave for a follow up post.  Before getting into reading that, consider how you would approach putting together an inheritable list class for all of these various DatabaseObjects created here.  What sort of shared methods could this list employ?</p>
<p>When you start to think in those terms, you are developing in an Object Oriented style.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/metrol.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/metrol.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metrol.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metrol.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metrol.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metrol.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metrol.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metrol.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metrol.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metrol.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=14&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metrol.wordpress.com/2008/03/13/php-database-creating-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a26c380e3f4214e0f4e501b5a1dfa5ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">metrol</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Namespaces</title>
		<link>http://metrol.wordpress.com/2008/03/11/php-namespaces/</link>
		<comments>http://metrol.wordpress.com/2008/03/11/php-namespaces/#comments</comments>
		<pubDate>Wed, 12 Mar 2008 03:44:58 +0000</pubDate>
		<dc:creator>Michael Collette</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[pecl]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://metrol.wordpress.com/?p=13</guid>
		<description><![CDATA[Upcoming PHP namespaces.  Discussion for what this means to developers.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=13&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the major issues that Object Oriented design addresses is the problem of having tons of functions and variables all in the same global name space.  By modularizing the code you don&#8217;t run into the problem of having obnoxiously long function and variable names.  More modularized code means it&#8217;s far easier to reuse later on different projects without conflict.</p>
<p>While that might seem like the end of the story, it isn&#8217;t be any means.  As a project grows and starts into using elements of other projects you suddenly find yourself with a whole new naming problem.  Now those classes are starting into getting those obnoxiously long names.  Other OOP languages that are more established in this realm, like <a href="http://www.sun.com/java/" target="_blank" title="Sun's Java site">Java</a> and <a href="http://www.python.org/" title="Official Python site" target="_blank">Python</a>, have implemented solutions to these problems long ago.  It seems that PHP is finally starting to address this.<span id="more-13"></span></p>
<p>I personally didn&#8217;t think we would see PHP release this until version 6, but it looks like as of PHP 5.3.0 you can start into working with defining <a href="http://en.wikipedia.org/wiki/Namespace" title="Wikipedia article about namespaces" target="_blank">namespaces</a>. To quote the PHP manual&#8230;</p>
<blockquote><p><a href="http://http://us2.php.net/manual/en/language.namespaces.php" target="_blank" title="PHP Manual - Namespaces">Namespaces are available in PHP as of PHP 5.3.0. This section is experimental    and subject to changes.</a></p></blockquote>
<p>To better get a handle on what this is all about comes from a post by Dmitry Stogov to the PHP Internals mailing list.</p>
<blockquote><p><a href="http://marc.info/?l=php-internals&amp;m=118355320225178&amp;w=2" target="_blank" title="Dmitry's post on July 4th, 2007">[PHP-DEV] Simple Namespace Proposal</a></p></blockquote>
<p>The full thread is well worth the read since these were many of the formative arguments that have lead to what is in there today, and what will likely be where things are at when the dust settles.</p>
<p>As interesting as all of this is, namespaces are still not a part of the the stable PHP release just yet.  It&#8217;s very likely that it will be months even after 5.3.0 hits the streets before web hosts are fully upgraded.  There are also a number of unresolved issues facing the PHP developers.  One such problem is noted in a post on the PHP manual concerning the namespace rules.</p>
<blockquote><p><a href="http://us2.php.net/manual/en/language.namespaces.rules.php#80192" title="Comment from Dennis about namespace problems" target="_blank">Sadly enough, the latest class name resolution rules render PHP namespaces quite useless.</a></p></blockquote>
<p>Let&#8217;s face it, not only do us users of PHP have namespace issues, the language itself is getting out of control.  I can remember back when <a href="http://us3.php.net/quickref.php" title="PHP Function Quick Reference" target="_blank">this list</a> would nearly fit on a single page with two columns.  Everything on there exists in the global namespace.  As PHP continues to grow and add functionality are we forever going to see the function list grow?</p>
<p>Java dealt with this problem early on by keeping the core functionality of the language to a bare minimum, then distributing <a href="http://java.sun.com/docs/books/tutorial/java/package/index.html" title="Sun's Java tutorial concerning packages" target="_blank">libraries in the form of packages</a> that each exist within a namespace.  It may be that with the combination of a more complete object model and the need to add core functionality PHP may be forced into that type of model. If a packages style model is in the works, it&#8217;s most likely out there on the fringes of a PHP7 wish list that I haven&#8217;t seen yet.</p>
<p>My first immediate concern as I got looking into this was how autoloading would be impacted.   I use autoloading for all my class imports, so this is near and dear to my heart.  Searching about I found the following post discussing this.  The interesting stuff is in the follow up replies, so be sure to check out the full thread.  It&#8217;s only a couple of messages.</p>
<blockquote><p><a href="http://marc.info/?l=php-internals&amp;m=120429739728318&amp;w=2" title="Post by Fredrik Holmstr" target="_blank">[PHP-DEV] PHP 5.3 Autoload+Namespaces+Functions incorrect (atleast weird) behavior.</a></p></blockquote>
<p>I then ran across a blog entry by <a href="http://blog.agoraproduction.com/" title="David Coallier's blog" target="_blank">David Coallier</a> discussing namespaces and their usage.  Within the comments he addresses autoloading.  Many of the other comments express a pretty negative set of opinions about what Dmitry has worked up here.</p>
<blockquote><p><a href="http://blog.agoraproduction.com/index.php?/archives/47-PHP-Namespaces-Part-1-Basic-usage-gotchas.html#c647" target="_blank">Autoloading comment on David Coallier&#8217;s blog</a></p></blockquote>
<p>Whatever the final direction of this goes, it&#8217;s important to keep in mind that PHP started as a fairly simple procedural scripting language.  What we&#8217;re seeing now are the growing pains associated with becoming a platform that can readily handle much larger projects than would be practical today.  Look for all of this goodness to be hitting mirrors <a href="http://wiki.php.net/todo/php53" title="PHP 5.3.0 Todo List and Schedule" target="_blank">near you very soon</a>.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/metrol.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/metrol.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metrol.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metrol.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metrol.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metrol.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metrol.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metrol.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metrol.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metrol.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=13&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metrol.wordpress.com/2008/03/11/php-namespaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a26c380e3f4214e0f4e501b5a1dfa5ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">metrol</media:title>
		</media:content>
	</item>
		<item>
		<title>Eval Quote</title>
		<link>http://metrol.wordpress.com/2008/03/08/eval-quote/</link>
		<comments>http://metrol.wordpress.com/2008/03/08/eval-quote/#comments</comments>
		<pubDate>Sun, 09 Mar 2008 00:13:42 +0000</pubDate>
		<dc:creator>Michael Collette</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[eval]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[quote]]></category>

		<guid isPermaLink="false">http://metrol.wordpress.com/?p=12</guid>
		<description><![CDATA[The online PHP manual is perhaps one of the finest of it&#8217;s kind anywhere on the web for a programming language. The core information is pretty good, but the user comments that have accumulated over the years really fills in the gaps. Every once in a while a zinger gets tossed in there, and this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=12&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The online PHP manual is perhaps one of the finest of it&#8217;s kind anywhere on the web for a programming language.  The core information is pretty good, but the user comments that have accumulated over the years really fills in the gaps.  Every once in a while a zinger gets tossed in there, and this one got a chuckle out of me.</p>
<blockquote><p><i>&#8220;If eval() is the answer, you’re almost certainly asking the wrong question.&#8221;</i></p></blockquote>
<p>Not sure who originally said this, but it is surely sage advice.  You can see this in <a href="http://us3.php.net/manual/en/language.oop5.visibility.php#78432" target="_blank" title="PHP Manual - Visibility of methods and members">context here</a> if you&#8217;re so inclined.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/metrol.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/metrol.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metrol.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metrol.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metrol.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metrol.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metrol.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metrol.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metrol.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metrol.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=12&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metrol.wordpress.com/2008/03/08/eval-quote/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a26c380e3f4214e0f4e501b5a1dfa5ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">metrol</media:title>
		</media:content>
	</item>
		<item>
		<title>A Different Kind Of DB Abstraction</title>
		<link>http://metrol.wordpress.com/2008/03/08/a-different-kind-of-db-abstraction/</link>
		<comments>http://metrol.wordpress.com/2008/03/08/a-different-kind-of-db-abstraction/#comments</comments>
		<pubDate>Sat, 08 Mar 2008 23:50:51 +0000</pubDate>
		<dc:creator>Michael Collette</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[abstraction]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[update]]></category>

		<guid isPermaLink="false">http://metrol.wordpress.com/?p=11</guid>
		<description><![CDATA[This is something wonderfully straight forward in putting together a really nice SELECT statement in SQL. There&#8217;s all your data just flowing back out at you in the order you asked for. Slap together your HTML around it with PHP and you&#8217;ve got yourself a dynamic web page. If you&#8217;ve been doing this PHP thing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=11&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is something wonderfully straight forward in putting together a really nice SELECT statement in SQL. There&#8217;s all your data just flowing back out at you in the order you asked for. Slap together your HTML around it with PHP and you&#8217;ve got yourself a dynamic web page.</p>
<p>If you&#8217;ve been doing this PHP thing for more than a project or two you have certainly noticed the mess that is the database functions. An entire stack of functions for MySQL, Microsoft SQL, ODBC, PostgreSQL, etc. Sure, PHP is rich in interfaces to a wide variety of database platforms, but trying to change which platform your using can be a little nightmare. Were you supposed to run mysql_query() or pg_query()? Like many of you, I put together a little set of abstraction tools that we&#8217;re pretty much a set of functions that added a layer between the code that needed the data and the database itself. Now that PDO is on the scene it would seem that these kinds of custom libraries are no longer needed.</p>
<p>There is still a place for creating your own libraries though. Implementing tools that push the SQL into the background and allow you to focus on your logic and presentation. In this article I will share some methods I use to abstract UPDATES and INSERTS.<span id="more-11"></span></p>
<h1>Not So Friendly SQL</h1>
<p>Most of the web projects I work on require a lot of data lookups from a database. This really hits home with the publicly viewable pages where data lookups are critical to performance. On the other hand, the data needs to get in there somehow in the first place. The need for content management screens has always been a part of any dynamic web site.</p>
<p>As a developer I really used to hate dealing with forms. Those darn things are just filled with bugs the moment you start in to them. A few of the pitfalls in dealing with them&#8230;</p>
<ol>
<li>Setting the max length on input fields</li>
<li>Checkboxes that don&#8217;t pass anything along if not checked</li>
<li>Basic validation</li>
<li>Filling in values for editing</li>
<li>Does the database need to UPDATE or INSERT</li>
</ol>
<p>This list could go on for a while. I used to deal with these things manually, and without exception I always ran into issues with the UPDATE and INSERT actions. I&#8217;d quote an integer, or forget to quote a string, or some other typo would stop the process. I think I have spent more time debugging forms than any other kind of code. Then when you consider what a nasty set of security glitches can happen when a user gets to enter data into your code&#8230; yuck!</p>
<h1>It Was Always Right There</h1>
<p>So one day I got to looking at the database tables that I was using on a project. It sort of just hit me that almost everything I needed to know about my forms was just sitting there in the database.  I created those tables to reflect the kind of data I would need to display, and the forms to get that data in there.  Every field in the table had a clue as to what I was going to do with that data.</p>
<p>It was one of those huge, &#8220;well duh!&#8221; moments.  Something so obvious that I&#8217;ve been overlooking it for far too long.  So how do I put this to use?</p>
<p>I can tell you right now that this approach isn&#8217;t a catch all for every kind of data updating.  If your site is getting hammered with updates and inserts you most likely don&#8217;t want any kind of abstraction going on.  You certainly don&#8217;t want to waste time looking in the database to see what data needs to go in.  You&#8217;ll want to have hard coded what fields are getting data.  To make what I&#8217;m about to discuss work you need to run an additional query on the database to figure out what goes where, then you can follow that up with putting data in.</p>
<p>For the bulk of the work I do I&#8217;m usually not that concerned with squeezing the last performance drop out of putting data into the database.  Usually there are only a handful of people who are authorized to enter data, so I&#8217;m not looking at a bottleneck for most data writing.  A small performance hit is acceptable here for some big integrity and simplification gains.</p>
<h1>What You Know About Your Data</h1>
<p>I mostly work with MySQL for my web site needs.  Despite some very good arguments against using them, I almost always have an auto incrementing field acting as my primary index.  Again, this is not for a site getting hammered with updates.  The only type of table I wouldn&#8217;t have a primary index for would one that I flush the entire table out before importing new data.  A feed from another site or alternate data source for example.  It&#8217;s safe to say that every other table in use will have that primary index field in there.</p>
<p>I also know that if my updating routine is not passed a value for this primary index, then I&#8217;m looking at performing an INSERT.  When an index is passed along I know an UPDATE is needed, since I wouldn&#8217;t have had that index value unless a record already existed. Pretty basic stuff.</p>
<p>Every other field in a table is going to be of some &#8220;type&#8221;.  This could be a varchar, integer, or any other valid MySQL field type.  From the stand point of figuring out how to dynamically put together the SQL from PHP I don&#8217;t need to get that specific.  I do need to know some basics though.</p>
<ul>
<li>I need to know if the type should be expecting a string or not, since I need to know if quotes around the value are needed.</li>
<li>If a string is of a particular size, like a varchar(120), then I&#8217;ll want to make sure I don&#8217;t try to put more than the value needed.</li>
<li>Integer and float types better not be getting letters stuffed in there.</li>
<li>A float can have a decimal, an integer can&#8217;t.</li>
<li>All strings should be run through the appropriate escape routines so invalid characters don&#8217;t muck up the SQL.</li>
<li>Dates and times need a bit of special handling to make sure they&#8217;re in the correct format.</li>
<li>Which field is the primary key.</li>
</ul>
<p>From that criteria I determined that what I needed was 4 basic field types that my code could utilize, rather than trying to have a special case for every kind of MySQL type.  Also, this allows for abstracting to other databases that have an even larger variety of field types.  The types in question are:</p>
<ol>
<li>string</li>
<li>integer</li>
<li>float</li>
<li>date</li>
</ol>
<p>To handle the conversion between the MySQL field type and the one that I will be using I just put together an associative array to handle this.</p>
<pre>$dataTypes = array("tinyint"   =&gt; "integer", "smallint" =&gt; "integer",
                   "mediumint" =&gt; "integer", "int"      =&gt; "integer",
                   "bigint"    =&gt; "integer",
                   "float"     =&gt; "float",   "decimal"  =&gt; "float",
                   "double"    =&gt; "float",
                   "varchar"   =&gt; "string",  "text"     =&gt; "string",
                   "char"      =&gt; "string",
                   "datetime"  =&gt; "date",    "date"     =&gt; "date",
                   "time"      =&gt; "date");</pre>
<p>I realize there are more field types then this, but these are the ones I personally utilize most often.  Besides, I&#8217;m not going to do ALL the work for you.  What fun would that be?</p>
<h1>Looking Up What To Look Up</h1>
<p>So this article doesn&#8217;t turn into a full blown book here I&#8217;m going to focus in on how to do this with those old style MySQL functions.  I&#8217;m also going to put this together with a set of functions, though this really works better within the framework of an object.  You&#8217;re going to want to tweak this to your needs, and there&#8217;s certainly more work than just throwing PDO at it to fully abstract multiple databases.</p>
<p>I&#8217;m going to assume that you&#8217;ve already established a connection to your database and have a resource pointer for it.  I&#8217;ll call it $dbPtr here.  This also assumes you have a table with a primary index and some fields of various types.  We&#8217;ll just call this &#8220;InfoTable&#8221;.</p>
<p>With all the disclaimers out of the way, let&#8217;s get that field information from the table, which we&#8217;ll be using later.  To do this I&#8217;m going to run a query out to the database asking for all the columns, or fields, from the specified table.  This is probably the fastest way to get everything we need out of there since we&#8217;re only making one request to the database server. I will then examine each field as it comes out to determine which of my four basic field types each one of these fits into.</p>
<p>When field types come out of MySQL they may contain an attribute, like &#8220;varchar(120)&#8221;.  From the perspective of what I&#8217;m trying to do here these are two valuable pieces of information, so I need extract that number as the &#8220;size&#8221; of the field and get &#8220;varchar&#8221; by itself so I just have the type.  Once the type is known, I then look it up in my $dataTypes array for my more generic type.</p>
<pre>function dbFields_mysql($table)
{
  global $dbPtr;
  $fieldList  = array();
  $fieldIndex = "";
  $dataTypes  = array("tinyint"   =&gt; "integer", "smallint" =&gt; "integer",
                      "mediumint" =&gt; "integer", "int"      =&gt; "integer",
                      "bigint"    =&gt; "integer",
                      "float"     =&gt; "float",   "decimal"  =&gt; "float",
                      "double"    =&gt; "float",
                      "varchar"   =&gt; "string",  "text"     =&gt; "string",
                      "char"      =&gt; "string",
                      "datetime"  =&gt; "date",    "date"     =&gt; "date",
                      "time"      =&gt; "date");

  // Go out and hunt down all that field information
  $query = "SHOW COLUMNS FROM $table";
  $queryResource = mysql_query($query, $dbPtr);

  // Run through it all and fill in the fieldList and fieldIndex vars
  while ( $row = mysql_fetch_assoc($queryResource) ) {
    $field = $row["Field"];
    $prop  = $row["Type"];
    $key   = $row["Key"];

    // Look for a value stored in parenthesis
    $sizeStart  = strpos($prop, "(") + 1;
    $sizeLength = strpos($prop, ")") - $sizeStart;

    if ($sizeStart &gt; 1) {  // We have a parenthesis
      $type = substr($prop, 0, $sizeStart - 1);
      $size = substr($prop, $sizeStart, $sizeLength);
    } else {               // No parenthesis, so set the size to zero
      $type = $prop;
      $size = 0;
    }

    // Look for a space in the Type, as that is used to specify unsigned
    // or some other type of attribute for this field.
    if ( strpos($prop, " ") ) {
      $attrib = substr($prop, strpos($prop, " ") + 1);
    } else {
      $attrib = FALSE;
    }

    // Assign the generic data type as the type we'll be storing in the
    // returned array.
    if ( array_key_exists($type, $dataTypes) ) {
      $type = $dataTypes[$type];  // Assign a generic data type
    }

    // Assign what we've discoverd to the fieldList array
    $fieldList[$field]["type"]   = $type;
    $fieldList[$field]["size"]   = $size;
    $fieldList[$field]["attrib"] = $attrib;

    // Note if this is the primary key or not
    if ($key == "PRI") {
      $fieldList[$field]["key"]  = TRUE;
    } else {
      $fieldList[$field]["key"]  = FALSE;
    }
  }

  // Send it all back to the caller
  return $fieldList;
}</pre>
<h1>Using What The Database Told Us</h1>
<p>Thanks to that dbFields_mysql() function we now know what is allowed to go into the database.  We know the type, the size, and the attribute of each field.  We even know which field is the primary index.</p>
<p>Although this post is about simplifying the construction of INSERT and UPDATE operations, you should also consider what else you can do with this.  You could put together routines that know exactly what the maximum length of an input field should be on a form.  Upon submitting you can use this information to validate that numbers are where they need to be, and strings where they need to be.  All of this is now dynamically figured out, greatly reducing the amount of code needed to run basic validation.  This may be a fine subject for a new article, but for now let&#8217;s get back to slapping some data into the database.</p>
<p>Normally you would take all the information coming in from a form submission and go about constructing your SQL with that.  New records would get all the <a href="http://dev.mysql.com/doc/refman/5.0/en/insert.html" title="MySQL Manual - INSERT Syntax" target="_blank">INSERT syntax</a>, where existing records get all that <a href="http://dev.mysql.com/doc/refman/5.0/en/update.html" target="_blank">UPDATE syntax</a>.  Of course, neither of these two look anything like the other.  You would either create 2 sections of code to handle each, or perhaps utilize the <a href="http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html" target="_blank">INSERT ON DUPLICATE KEY UPDATE</a> utility.  When I&#8217;m trying to get data stored I just don&#8217;t want to deal with the hassle of the syntax intricacies involved with any of this.  I&#8217;ve got this data that needs to go in these fields, just do it already!</p>
<p>What if we could just match up the data to the fields, then let some other bit of code deal with putting together the SQL. How about a nice dbUpdate() function?  We&#8217;d have to tell it what table we want to update, as well as the data itself.  Also need to give it the value of our primary index when we&#8217;re doing an edit.  Okay, I can deal with that:</p>
<pre>$tableData = array("name"    =&gt; $name,
                   "address" =&gt; $address,
                   "state"   =&gt; $state,
                   "zip"     =&gt; $zip,
                   "salary"  =&gt; $salary,
                   "friend"  =&gt; $friend);
$indexValue = 3;
$tableName = "InfoTable";
 // All the data is together, so update the database
$returnIndex = dbUpdate($tableName, $tableData, $indexValue);</pre>
<p>This is pretty much all the code you&#8217;d need to update this person in our make believe table.  No need to check for strings being properly escaped, or whether quotes are needed.  Even check boxes are dealt with properly.  Leave out the $indexValue, or set it to zero, and it runs an INSERT automatically.  It&#8217;s also far easier to read than the SQL you would normally use, thus making typos a little less likely. Even a typo won&#8217;t stop this from working, as we know what fields are allowed.  We can weed out fields that don&#8217;t really exist.</p>
<h1>Constructing The SQL</h1>
<p>Now that you&#8217;ve seen what an INSERT or UPDATE would look like using this dbUpdate() routine, let&#8217;s get into actually coding some of this up.  Be warned up front, I have not thrown in all of the data validation that can be done here.  My intention is to show the technique, not put together a ready to use package.</p>
<pre>function dbUpdate($table, $fldValArray, $indexValue=0)
{
  global $dbPtr;
  $q = "";
  $indexValue = intval($indexValue); // Make sure this is an integer

  // Make sure we've at least got the minimum stuff to run this
  if (strlen($table) &lt; 2 or count($fldValArray) == 0) {
    return FALSE;
  }

  $fieldList = dbFields_mysql($table); // Load up all the stuff we need to know
                                       // about the fields in this table.

  if (count($fieldList) &lt; 1) {  // doesn't look like we have a field list
    return FALSE;
  }

  if ($indexValue != 0) {  // Do we need to know which is the primary key?
    // Yes we do.  Find it!
    $primaryKey = "";
    foreach ($fieldList as $field =&gt; $value) {
      if ($fieldList[$field]["key"]) {
        $primaryKey = $key;
      }
    }
    if ( !$primaryKey ) { // An index value, but no primary key... ERROR!
      return FALSE;
    }
  }

  if ($indexValue &gt; 0) {  // With an index value we need to UPDATE the table

    $q  = "UPDATE $table\n";
    $q .= "SET\n";

    foreach ($fldValArray as $field =&gt; $value) {

      if ( array_key_exists($field, $fieldList) ) { // Only run for valid fields

        switch ( $fieldList[$field][$type] ) { // Prepare the value based on the type of field

          case "string":
            $value = strval($value);
            $value = trim($value);
            if ( $fieldList[$field]["size"] &gt; 0 ) {  // Chop it down to size
              $value = substr($value, 0, $fieldList[$field]["size"]);
            }
            // Make sure we've got a clean input
            $value = mysql_real_escape_string($value, $dbPtr);
            $q .= "$field = \"$value\",\n";
          break;

          case "date":
            $value = strval($value);
            $value = trim($value);
            $q .= "$field = \"$value\",\n";
          break;

          case "integer":
            $value = intval($value);
            $q .= "$field = $value,\n";
          break;

          case "float":
            $value = floatval($value);
            $q .= "$field = $value,\n";
          break;

          default:
            $q .= "$field = \"$value\",\n";
        }
      }
    }
    $q = substr($q, 0, -2); // Strip the last comma and line feed off
    $q .= "\nWHERE ".$primaryKey." = ".$indexValue;

    $qr = mysql_query($q, $dbPtr); // Run the update

  } else { // No id passed, so put together an INSERT

    $fldStr = "(";  // Begin the field section of the INSERT
    $valStr = "(";  // Begin the values section

    foreach ($fldValArray as $field =&gt; $value) {

      if ( array_key_exists($field, $fieldList) ) { // Only run for valid fields

        $fldStr .= $field.", ";

        switch ( $fieldList[$field][$type] ) {

          case "string":
            $value = strval($value);
            $value = trim($value);
            if ( $fieldList[$field]["size"] &gt; 0 ) {
              $value = substr($value, 0, $fieldList[$field]["size"]);
            }
            $value = mysql_real_escape_string($value, $dbPtr);
            $valStr .= "\"$value\", ";
          break;

          case "date":
            $value = strval($value);
            $value = trim($value);
            $valStr .= "\"$value\", ";
          break;

          case "integer":
            $value = intval($value);
            $valStr .= "$value, ";
          break;

          case "float":
            $value = floatval($value);
            $valStr .= "$value, ";
          break;

          default:
            $valStr .= "$value, ";
        }
      }
    }
    $fldStr = substr($fldStr, 0, -2).")"; // Strip comma and add a closing ")"
    $valStr = substr($valStr, 0, -2).")"; // Strip comma and add a closing ")"

    $q  = "INSERT INTO $table\n";
    $q .= $fldStr."\nVALUES\n".$valStr;

    $qr = mysql_query($q, $dbPtr);   // Run the INSERT
    $indexValue = mysql_insert_id(); // Pull in the primary key ID
  }

  return $indexValue;
}</pre>
<p>So let&#8217;s walk this through step by step.</p>
<p>The indexValue defaults to 0 so that can be an optional argument.  I then make sure that this is an integer no matter what.</p>
<p>So things don&#8217;t totally go awry I check that a table and some data has been passed on in here.</p>
<p>I then populate my fieldList array with the dbFields_mysql() function shown earlier.  That fieldList array has everything I need to know about getting this SQL together.  I then make sure something is loaded in that array before I let this go any further.  There may be a typo with the table name.</p>
<p>I only need to know which field is the primay key if I&#8217;m going to update this record, which means I only need to hunt it down if indexValue has a value.  If it does, I then store the name of this field as $primaryKey.</p>
<p>The next big section is broken into two segments depending on whether an index value exists.  The first section puts together and updates the database.  The second does almost the same thing for an insert.  Both sections utilize a switch/case setup to determine what kind of clean up and formatting is needed for each field.  If the field this function has been asked to update doesn&#8217;t exist, it doesn&#8217;t add it to the SQL.</p>
<p>Whether an UPDATE or an INSERT take place you always get back the value for the primary index.</p>
<h1>What Is Missing</h1>
<p>This isn&#8217;t exactly the code I use in production since I have further abstraction going on within a class usually.  I didn&#8217;t want to get into the full framework I use right here, so I presented a procedural approach to this.  Utilizing an object oriented approach allows me to store the field list and primary index as member data, so I normally don&#8217;t have to dig that kind of stuff out.</p>
<p>The worst bug in this version is that it doesn&#8217;t take into account what to do if none of the fields being requested to update exist.  If you do run into a situation like this I would recommend that you stop trying to type with your elbows and start working with your fingers.  Seriously though, a solid function should anticipate this and deal with it.</p>
<p>You could also work in much tighter controls on numeric and date fields to further validate what is going in to make sure the values are not jumping out of bounds and are in the correct format.  I left that out of there in this example to keep things brief.</p>
<h1>Does It Work?</h1>
<p>Since putting this together into a class I&#8217;ve found that I rarely have to write INSERT or UPDATE syntax.  I&#8217;ve also spent very little time having to debug why an update to the database has failed.  These functions are tightly aligned to how I put together my database tables which stay pretty consistent between projects, so it&#8217;s worked out very nicely for me.  Yes, there is a slight performance cost, as I have already discussed, but not one that&#8217;s noticeable under a light updating load.</p>
<p>To apply this to other database engines you will want to do more than just use a simple abstraction layer like PDO.  Each one has different field types and ways in which to extract the field information from them.  Still, there&#8217;s no reason why you couldn&#8217;t duplicate this effort for another engine with a simple wrapper function to decide which bit of code needs to run for which engine.  Once you have established a call to user defined functions as your means to talk to your database, you won&#8217;t have to go revisit that code again.</p>
<h1>Summary</h1>
<p>I hope I&#8217;ve provided to you a different way of approaching getting data into your database.  By creating functions or methods for handling this task I believe you will simplify your code, provide for better data integrity, and generally make the world a more wonderful place.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/metrol.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/metrol.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metrol.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metrol.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metrol.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metrol.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metrol.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metrol.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metrol.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metrol.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=11&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metrol.wordpress.com/2008/03/08/a-different-kind-of-db-abstraction/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a26c380e3f4214e0f4e501b5a1dfa5ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">metrol</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP &#8211; From Procedural to Object Oriented</title>
		<link>http://metrol.wordpress.com/2008/03/08/php-from-procedural-to-object-oriented/</link>
		<comments>http://metrol.wordpress.com/2008/03/08/php-from-procedural-to-object-oriented/#comments</comments>
		<pubDate>Sat, 08 Mar 2008 02:29:57 +0000</pubDate>
		<dc:creator>Michael Collette</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://metrol.wordpress.com/2008/03/08/php-from-procedural-to-object-oriented/</guid>
		<description><![CDATA[An object oriented tutorial for procedural PHP developers<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=10&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I hated the notion of <a href="http://en.wikipedia.org/wiki/Object_oriented" title="Wikipedia article about Object Oriented programming" target="_blank">Object Oriented (OO) programming</a>. I&#8217;d been using <a href="http://php.net/" title="Official PHP Website" target="_blank">PHP</a> since early version 3, and I had put together some very usable web sites with it. Every book I read on the topic seemed to be rich with metaphors about dogs, cars, and various other things, but not much on why I would want to abandon my happy <a href="http://en.wikipedia.org/wiki/Procedural_programming" title="Wikipedia article about Procedural Programming" target="_blank">procedural methods</a>. Not that these authors didn&#8217;t try. The arguments they made just didn&#8217;t hit home with me at the time.</p>
<p>I think I may now understand why this was. Most of the efforts I&#8217;ve seen to describe object oriented design are coming from the perspective of someone who thinks in an OO way. I&#8217;m not saying this was a bad approach, it just really didn&#8217;t work for me. Perhaps if I hadn&#8217;t been so deeply entrenched in the methodologies I had been using for years I would have been more receptive to this type of presentation.</p>
<p>I don&#8217;t have any better arguments here for designing in an OO way, but I believe this article approaches the topic from an angle that might make things a bit clearer for people like me. Programmers who have been putting together working sites in a procedural manner and can&#8217;t seem to make the mental hurdle into OO.<span id="more-10"></span></p>
<p>Mind you, if we were still talking about PHP4 avoiding OO would have been a good thing. It really was a hack job slapping on only some of the most basic functionality for objects. It was bad enough that many of the ways you would have done things in version 4 are now, thankfully, obsolete. PHP5 has finally started making it real.</p>
<p>The issue with learning how to deal with objects isn&#8217;t in the syntax or the mechanics. I can promise you, once you get a handle on the concept of OO design the mechanics darn near write themselves. Much of it is just a matter of rethinking much of what you already know. Perhaps learning a few new terms along the way.</p>
<p>The real key to your understanding of Object Oriented programming is purely in getting the concept of it. This article intends to focus on concept rather than functioning code. I will be leaving a bunch of details out that I believe will hinder your grasping of the concepts. Many of these are better handled by some of the books I&#8217;ve referenced at the end of the article or the PHP manual online.</p>
<p>I will begin by taking you through some of the problems you may have already experienced with a purely procedural approach to your design. One by one I hope to address how what appear to be problems in procedural land are actually features of designing in an Object Oriented way.</p>
<h1> Development Stages of a Developer</h1>
<p>Looking back on it now I went through a set of stages in my thinking and development habits as the projects I worked on got larger. It is not, as many people might lead you to believe, because an OO design strategy is only useful on a large project. It is due to the fact that many of the pitfalls of writing purely procedural code don&#8217;t really become readily apparent until you are dealing with a larger set of code. They become screamingly obvious once you start working on the next project needing similar code as the one before.</p>
<p>If you&#8217;ve been working with PHP for a while you may recognize some of these stages. I know I went through each and every one of them, and I know others who have done much of the same.</p>
<h2> Stage 1</h2>
<p>You&#8217;ve got your script talking to a database. You&#8217;ve got forms collecting data, and clever SQL and loops producing that data into something presentable. Your PHP code and HTML are coexisting in harmony on all of these wonderful dynamic pages. There is much rejoicing.</p>
<h2> Stage 2</h2>
<p>The harmony that had existed has started to vanish. The data and the pages they are producing are becoming more complex. Worse still, trying to work out what code is doing a few months after you wrote it has become more of a headache than writing new code. It&#8217;s time to move as much of the logic as possible into functions.</p>
<h2> Stage 3</h2>
<p>Moving the logic into functions has proven to be a beautiful thing. You&#8217;ve started to create libraries of these functions which you include when you need them. You may have a set of core functions that you use on multiple projects, site specific items, perhaps some database handling routines. New features mean new functions that grow into new libraries of them. It&#8217;s all under control.</p>
<h2> Stage 4</h2>
<p>The functions are working still, but not all is well in paradise. With all of these functions about you have started giving them wonderfully descriptive names like &#8220;PullProductInfoFromDatabaseInHTML()&#8221;. It&#8217;s starting to get a little nutty so you don&#8217;t run into naming conflicts with functions written long ago.</p>
<p>With all of these functions in various files you&#8217;ve been including it&#8217;s also getting harder to track down which file has a specific function. While looking for a lost function you also find that you&#8217;re running across long forgotten functions you&#8217;re no longer sure are even still being used.</p>
<p>Things have started to get a little painful, but you&#8217;ve got it under control. Just a little filing issue really. Just need to start writing a little documentation for all of those functions. Documentation that, even as you write it, you know doesn&#8217;t stand a prayer of staying up to date.</p>
<h2> Stage 5</h2>
<p>You start up a new project that is similar to a previous one, so you want to use those function libraries over again. Problem is, too many of those functions were tied so closely to the previous project that you end up having to edit those functions in place. Not a bad deal initially, except that now you have two sets of the very same functions with minor tweaks between them. Enough minor tweaks, and you can&#8217;t use those libraries over again.</p>
<p>Now you not only have the problem of figuring out what function is in which file, but now you also need to identify which group of files has the up to date versions that you&#8217;ve got all optimized and working better than the earlier versions.</p>
<h2> Stage 6</h2>
<p>What had started out so elegant in it&#8217;s simplicity has turned into a mess of complexity. Everything is in the global namespace, so you&#8217;re spending as much time trying to name new functions and variables as you are actually programming. Your once good friends, “Copy&amp;Paste”, have actually made your life more, not less, complicated.</p>
<h1>The Problem with Functions:  Part I &#8211; Context</h1>
<p>If you will, journey back with me a bit to Stage 4 mentioned previously. Consider for a moment just what you are doing when you give your functions really long descriptive names. What broke down from when you could just write something like productInfo(), or even info()?</p>
<p>This gets into the first problem that needs to be addressed with functions, and that is context. You are trying to put some action into the context of what it is acting upon. By their very nature a function exists without a context of it&#8217;s own, so a fully procedural program has to work around this by getting clever with how functions are named. This can get real ugly real fast when you have multiple kinds of data that could really use a getName() procedure.</p>
<p>Jumping a bit further into metaphor land, you can think of a function as a verb without a noun. It&#8217;s purely an action statement. Like saying &#8220;run&#8221;, but not saying what is running.</p>
<p>One reasonably simple way to deal with this is to create a &#8220;class&#8221; that contains a set of your procedural functions. This is not an Object Oriented approach just yet, but it is a valuable building block.</p>
<p>Old function calls</p>
<pre>function pullProductInfoFromDatabaseInHTML()
{
  // Pretend to run query and return a result
  return "Acme 123 Motorized Widget";
}</pre>
<p>Doing the exact same thing with a static class.</p>
<pre>class Product
{
  public static function pullFromDatabaseInHTML()
  {
    // Pretend to run query and return a result
    return "Acme 123 Motorized Widget";
  }
}</pre>
<p>To run the old function you would just call it&#8217;s name and look for a result.</p>
<pre>$productInfo = pullProductInfoFromDatabaseInHTML();</pre>
<p>With our fancy new class you would instead say&#8230;</p>
<pre>$productInfo = Product::pullFromDatabaseInHTML();</pre>
<p>These two approaches do the exact same thing. The difference here is now we can group all of the functions dealing with a &#8220;Product&#8221; inside of this class. Now you can have numerous functions called pullFromDatabaseInHTML() for whatever kind of grouping of data that you wish with much less chance of a naming conflict.</p>
<p>With this alone, you could stick with the procedural style you&#8217;ve been doing and start to seriously simplify your naming schemes. Better still, you could pass the entire contents of this class to an entirely different project with a drastically reduced chance of a naming conflict. Better still, you can now import little libraries of these functions from other developers right into your code without conflict. Feeling all organized yet?</p>
<p>We haven&#8217;t got into anything involving objects or OO design as of yet. All we&#8217;ve done is provided a way to group a bunch of functions together. That is what a “static class” is all about. We&#8217;ll be doing quite a bit with classes here shortly. At this point just take this little tid bit with you before leaving this section.</p>
<ul>
<li>A class that has all of its functions defined as static is a “static class”.</li>
</ul>
<p>Now who could possibly argue with that?</p>
<h1> The Problem with Functions: Part II &#8211; State</h1>
<p>Let&#8217;s just pretend that you&#8217;ve put together a wonderful little library of functions into a class. The problem now is that each and every function has to call out to the database to get some of it&#8217;s information, every time. For example, if you wanted to have a dedicated function for getting a product&#8217;s name and one for the description, each one has to do their own lookup or come up with some means of sharing that information with the other functions.</p>
<p>There are 3 basic ways to get information into a function.</p>
<ol>
<li>Pass an argument in the call.</li>
<li>Define a variable as global.</li>
<li>Use a defined constant.</li>
</ol>
<p>To start with, is there anything more obnoxious than a function with a large number of arguments? I know I love trying to track down a function to figure out what order things went in. Worse still, trying to work out what values were supposed to go in there. It&#8217;s all I can do to try and remember if the haystack or needle comes first in <a href="http://us3.php.net/strpos" title="PHP Manual - strpos()" target="_blank">strpos()</a>. Let&#8217;s just say at this point that one of my new goals here is to limit the number of arguments that need to go into a function call.</p>
<p>You could dance around this problem by using lots of &#8220;<a href="http://us.php.net/global" title="PHP Manual - Variable scope" target="_blank">global</a>&#8221; statements in the functions, but then we&#8217;re back to the same old naming problems we ran into before we put things into a class. Yet another goal here is not just to have something that works, but to keep that global namespace as clean as can be. From this point forward we can just think of the “global” keyword as the work of the devil. It is an easy temptation that initially sounds good, but can only end poorly.</p>
<p><a href="http://us.php.net/manual/en/language.constants.php" title="PHP Manual - Defined Constants" target="_blank">Defined constants</a> can be used at any level of code. They can be really good stuff for setting up preferences and the like. Of course they&#8217;re not much good for the problem we&#8217;re running into here. They&#8217;re constants! You can&#8217;t change their value.</p>
<p>Getting information in or out of a function is quite limited. Oh sure you can toss an arrays around, but in doing so the caller has to know what the arrays will contain. More complexities! What you really want to be able to do is keep your functions small, easy to call to, and easy to understand what will come back out. To do that one thing it needs to do really well. Your also trying to hide the complexity of what is going on behind the curtain so you can focus on the larger picture of your project.</p>
<p>What you need is some reasonable way for related functions to share information with each other in some reasonable way. How do you do that? How would you try to solve this problem?</p>
<p>I believe it was this question that lead to the notion of creating an object in the first place. You&#8217;ve got this grouping of functions that not only need to remember stuff, but share that stuff amongst each other within that group of functions.</p>
<ul>
<li>An object is a library of functions that can remember and share stuff.</li>
</ul>
<h1>Okay, What Was That Again?</h1>
<p>My little definition of an object is worth repeating, but let&#8217;s instead repeat it using the proper terminology.</p>
<ul>
<li>An object is a library of “methods” that can remember stuff.</li>
</ul>
<p>When you stuff a function into a class it gets called a “<a href="http://en.wikipedia.org/wiki/Method_%28computer_science%29" title="Wikipedia article about methods">method</a>”. It acts in almost every way like a function. You stuff data into it with arguments, and you can get a single return value from it. It is a little different as you will see shortly.</p>
<p>To make matters even more confusing, in PHP you declare a “method” by calling it a “function”! This has got to be worse than clicking on Start to shut your computer down. I believe this has to do with legacy reasons more than anything else, as you certainly don&#8217;t see the keyword “function” used in a language like Java.</p>
<p>If calling a “function” a “method” wasn&#8217;t bad enough, now variables get a new name too. A variable that is declared within a class, but outside of a method, is called a “member”. It&#8217;s still a variable like you&#8217;d use outside the notion of a class. Saying something like $x=”Howdy” still means that $x is a string. Do that outside of a class and it&#8217;s just a string variable. Inside a class it&#8217;s referred to as a “member”, “data member”, or &#8220;instance variable&#8221;.</p>
<p>So why in the world do we have to rename perfectly good things like functions and variables when they&#8217;re put into a class? Remember, we&#8217;re trying to put together a group of methods that can use and share information within that group. That concept doesn&#8217;t really exist for functions hanging out in the global namespace.</p>
<p>To appreciate this difference let&#8217;s step back a bit and review some basics about what you know about a function.</p>
<pre>function adder($x, $y)
{
  $z = $x + $y;
  return $z;
}</pre>
<p>In this little adder() function we have 3 variables, all of which only exist while the function is running. In other words, the contents of this function exist within a little world of their own. The function can&#8217;t see anything outside the scope of it&#8217;s enclosing brackets. Data goes in, data comes out, but anything about what happened in between is lost once the function has completed.</p>
<p>We need to get together a class that not only has some methods, but also some members. You can think of this as the blueprint of creating an actual object. Hang on to that mouse, it&#8217;s about to get a little bumpy here.</p>
<h1>A Class Is Not an Object</h1>
<p>The first class example I showed you had a “<a href="http://us.php.net/manual/en/language.oop5.static.php" title="PHP Manual - Static keyword">static method</a>”, which essentially means you can just call that method directly with what them PHP folks call a “<a href="http://us.php.net/manual/en/language.oop5.paamayim-nekudotayim.php" title="PHP Manual - Scope Resolution Operator" target="_blank">Scope Resolution Operator</a>”, which is a really big fancy term for a pair of colons “::”.</p>
<p>We could just take everything in our Product class and make it static. What if we had to have two or more of those products at the same time? Consider a product catalog that needs to show lots of products on the same page. Wouldn&#8217;t it be cool to have a bunch of objects that could be created using the same class?</p>
<p>Turns out, this is exactly how it works! You use a class to define what an object should do and remember, then you create an object from that. I better slap some code here before I metaphor again.</p>
<p>A Product class that&#8217;s ready to be turned into an object:</p>
<pre>class Product
{
  public $model = “”;
  public $description = “”;</pre>
<pre>  public function pullFromDatabase($index)
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>So now what in the heck can we do with that? How about we finally go and make us an object with this thing already. Gather the family around, this part is really exciting.</p>
<pre>$p = new Product();</pre>
<p>Pretty cool huh? Okay, so you&#8217;ve got the kids and your aunt walking away in disgust at how dull that was. I guess they just can&#8217;t appreciate just how cool this really is. You have just made a bona fide object! So what can you do with this thing you just did? Well, you could run that method that is now a part of this object. How about let&#8217;s go and get a product record from the database with an index value of 12.</p>
<pre>$p-&gt;pullFromDatabase(12);</pre>
<p>Another big fat yawn you say? Well, now we have some values in those members. Here, let&#8217;s use them to show a model and description.</p>
<pre>print $p-&gt;model.” “.$p-&gt;description.”\n”;</pre>
<p>There&#8217;s some might funky looking syntax there with all that “-&gt;” stuff going on. This is PHP&#8217;s way of stating what context you mean. You created an object from the Product class and called it $p. Now to use that in your code you need to show that you mean the method or member from that object. Without saying “$p-&gt;” PHP is going to think you&#8217;re referring to the global namespace. Just saying “pullFromDatabase(12);” tells PHP go look for that as a function, not a method for an object.</p>
<p>I promised you a solution for when you needed more than one product didn&#8217;t I? You could just run that same database pull method, but then we just lost what that $p object knows. How about we instead just create a new Product object.</p>
<pre>$p1 = new Product();
$p1-&gt;pullFromDatabase(15);
print $p1-&gt;model.” “.$p1-&gt;description.”\n”;</pre>
<p>Now there&#8217;s 2 objects, $p and $p1, with different stuff they know. You could even put those objects into an array. Something I will illustrate after I explain a couple of goodies I tossed in that you may be wondering about if you&#8217;ve been watching closely.</p>
<h1>Which This Is $this</h1>
<p>Hopefully you&#8217;re wondering what those “$this-&gt;” is about. Before I can tell you that you&#8217;ll need some terminology thrown at you.</p>
<ul>
<li>The keyword “new” creates a new “instance” of an object.</li>
</ul>
<p>So what does that mean? Well, you created two objects from that Product class. Each one is considered an instance of that object. Each instance can all do the same things, but they all know different things. Lose you yet?</p>
<p>Our first object instance was $p. That instance has the model and description of that product. In other words, it knows something about that specific product we asked for. $p1 was another instance that also knows a model and description, but a different one than $p.</p>
<p>Even though each instance knows something different, they both have the same action, pullFromDatabase(). Two instances, two sets of data that they know, but one set of actions.</p>
<p>So how does “$this-&gt;” fit in? Outside the class we need to specify our created object before requesting something, like $p-&gt;model. Inside of the class when a method refers to one of the members it has to specifically state that it is a member of, and here it comes, “this” instance of the object.</p>
<p>If you had instead had a method that looked like the following you wouldn&#8217;t have gotten the result you expected.</p>
<pre>public function pullFromDatabase($index)
{
  // Fancy database query would run here
  $model       = $dataRow[“model”];
  $description = $dataRow[“description”];
}</pre>
<p>Methods are quite a bit like functions, in that variables declared within a method only exist within the scope of that method. PHP needs some way to have you tell it what you really mean is the member variable model, not a local one.</p>
<h1> Just Do It</h1>
<p>It seems kind of silly to have to create this new object, then tell it to pull some information out of the database. It would be nice to instead have it just do that when you create your new instance of the Product class. A perfect lead in to what PHP refers to as “Magic Methods”.</p>
<p>The PHP site doesn&#8217;t do a very good job at defining a <a href="http://us.php.net/manual/en/language.oop5.magic.php" title="PHP Manual - Magic Methods" target="_blank">Magic Method</a>, so I&#8217;ll do what I can here for you.</p>
<ul>
<li>A “<a href="http://us.php.net/manual/en/language.oop5.magic.php" title="PHP Manual - Magic Methods" target="_blank">Magic Method</a>” is a method that runs due to some action taken on an object.</li>
</ul>
<p>A Magic Method isn&#8217;t meant to be called directly. They happen when some kind of event is detected. These are methods that are already defined by PHP, so you don&#8217;t get to make new ones yourself. Our first of these methods happen when an object instance is constructed. Your just going to love the name of this&#8230; it&#8217;s called the “<a href="http://us.php.net/manual/en/language.oop5.decon.php" title="PHP Manual - Constructors and Destructors">constructor</a>”. All of these fancy methods start with two underscores, so as to avoid possible naming conflicts and perhaps to look a bit like Python. Anyone&#8217;s guess.</p>
<p>Let&#8217;s get a constructor slapped into our Product class already.</p>
<pre>class Product
{
  public $model = “”;
  public $description = “”;</pre>
<pre>  public function __construct($index)
  {
    $this-&gt;pullFromDatabase($index)
  }</pre>
<pre>  private function pullFromDatabase($index)
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>You now must pass an index value argument into the class when you construct a new instance object of this class. That&#8217;s a lot of syllables for saying you get to pass an argument on in when you create a new object. Here&#8217;s what that looks like.</p>
<pre>$p = new Product(12);</pre>
<p>There are two new little concepts I sneaked in here on you. First, notice how I needed to use that darn “$this-&gt;” operator to call the pullFromDatabase() method? Because it isn&#8217;t a static method, it belongs to the instance of this object. Trying to call it without “$this-&gt;” and you&#8217;ll get yourself a lovely little error message that the function can&#8217;t be found in the global namespace.</p>
<p>The second thing to notice is that I changed the first keyword on the pullFromDatabase from “public” to “private”. Why in the world did I do that? What does that mean?</p>
<h1> Locking Things Down</h1>
<p>Up until this point, everything I had in that class was public, meaning that anywhere this object existed a request to run that method could happen. From way out in the global namespace I could ask for that method to run. I&#8217;ve decided that I didn&#8217;t want just any old code to call my database routine, only my constructor. By marking that method “private” I&#8217;m saying only methods within this specific class can even see it, much less run it. An attempt to run it from anywhere else will kick off an error.</p>
<p>So why are we keeping secrets from other parts of our code? Aren&#8217;t we all friends here? What, you don&#8217;t trust me? Ah geesh, hurt my feelers why don&#8217;t ya.</p>
<p>In my mind there are a couple reasonable answers to the question of why you can and should lock down who is allowed to access a method.</p>
<ol>
<li>Classes are supposed to exist to simplify your life. A year after you&#8217;ve written your perfectly written class you aren&#8217;t going to want to dig through every method. You&#8217;re only going to want to know about the methods that you need to use that class. The public ones.</li>
<li>You may have an order in which different methods need to run that may not be entirely obvious from outside code. By marking those as private your public classes can insure things are run properly. This impacts the integrity of your program.</li>
<li>Some information that you use within a class may not be any other code&#8217;s business. For example, only your database connection class ever need know anything about a database password. Only your billing code ever need any kind of access to a credit card number. You can make things a bit more secure by locking down what parts of your program can be seen.</li>
</ol>
<p>Taking the next logical step here, let&#8217;s also lock down those members, or “instance variables”.</p>
<pre>class Product
{
  private $model = “”;
  private $description = “”;</pre>
<pre>  public function __construct($index)
  {
    $this-&gt;pullFromDatabase($index)
  }</pre>
<pre>  private function pullFromDatabase($index)
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>Oh great, now that only methods within this class can even look at those members how do we get them out of there? We slap together a couple of “accessor” methods to provide those to us.</p>
<pre>class Product
{
  private $model = “”;
  private $description = “”;</pre>
<pre>  public function __construct($index)
  {
    $this-&gt;pullFromDatabase($index);
  }</pre>
<pre>  public function getModel()
  {
    return $this-&gt;model;
  }</pre>
<pre>  public function getDescription()
  {
    return $this-&gt;description;
  }</pre>
<pre>  private function pullFromDatabase($index)
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>Now we&#8217;re starting to see a class that looks something like you would see in the real world. Data members that are private, but accessible via public methods. This is a form of &#8220;encapsulation&#8221;. We&#8217;re now in full control of how members are accessed or changed. In this case, only the pullFromDatabase() method is allowed to change the model and description.</p>
<p>So let&#8217;s jump back out into the global namespace realm again and put this to use.</p>
<pre>$p[0] = new Product(12);
$p[1] = new Product(13);
$p[2] = new Product(14);</pre>
<pre>foreach ($p as $productObj) {
  print $productObj-&gt;getModel().” “.$productObj-&gt;getDescription.”\n”;
}</pre>
<p>Oh sure that works, but it&#8217;s kind of ugly. All those “-&gt;” things really muck things up. There is a prettier way of doing this, and it works in my 2nd favorite Magic Method, “__toString()”. Let&#8217;s toss that into our rapidly growing class to see what it does.</p>
<pre>class Product
{
  private $model = “”;
  private $description = “”;</pre>
<pre>  public function __construct($index)
  {
    $this-&gt;pullFromDatabase($index);
  }</pre>
<pre>  public function __toString()
  {
    return $this-&gt;getModel().” “.$this-&gt;getDescription().”\n”;
  }</pre>
<pre>  public function getModel()
  {
    return $this-&gt;model;
  }</pre>
<pre>  public function getDescription()
  {
    return $this-&gt;description;
  }</pre>
<pre>  private function pullFromDatabase($index)
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>With our new Magic Method in place let&#8217;s see what our code would look like back from where we want to call this from.</p>
<pre>$p[0] = new Product(12);
$p[1] = new Product(13);
$p[2] = new Product(14);</pre>
<pre>foreach ($p as $productObj) {
  print $productObj;
}</pre>
<p>Ooooo, pretty! Creating our objects and assigning them to an array let us put together a quick list of those Products ready to foreach through them. All that yucky “$objName-&gt;methodCall()” stuff I now have tucked away into a Magic Method that is magically called when I print the object. You just gotta love that, if only a little.</p>
<h1>Take a Breather</h1>
<p>Let&#8217;s just stop right here and say that&#8217;s all there is to the story. If this were all there was to it and you wanted to put what we&#8217;ve discussed up to this point to use. What good is it?</p>
<p>To start with, we&#8217;ve got this wonderful mechanism for both grouping our methods within this fancy wrapper called a “<a href="http://en.wikipedia.org/wiki/Class_%28computer_science%29" title="Wikipedia article describing class" target="_blank">class</a>”. That alone pulls a ton of muck out of the global namespace. Not only have we organized functions that would have all been in the global space, but now those functions can actually remember stuff. We&#8217;ve got magical methods that get the ball rolling when you create an object, and put it all together when you need some output.</p>
<p>No matter how many different strings, integers, arrays, or functions you need to handle everything to do with products, none of them muck up your global namespace. This should also make it easier to name things, since the context is provided for by the class. Life is good.</p>
<p>And it gets better, because what I&#8217;ve shown you up to this point would allow you to make use of most of those fancy libraries in the <a href="http://pear.php.net/" title="The PEAR repository">PEAR repository</a>. Most everything in PEAR is made up of either object oriented classes or static classes. You would either create an object from them or call to them directly with that “::” notation. Even if you never write anything that goes into a class yourself, you can still use code that has been.</p>
<p>If all that wasn&#8217;t cool enough, by knowing how to access objects you also open yourself up to the highly dynamic world of <a href="http://en.wikipedia.org/wiki/SOAP" title="Wikipedia article about SOAP">SOAP, Simple Object Access Protocol</a>. SOAP is an impossibly cool technology that&#8217;s changing the face of development. I don&#8217;t want to get into this too much in this article, but here&#8217;s a bird&#8217;s eye view of it.</p>
<p>Imagine you wrote a really swell class with a stack of very useful methods. You&#8217;d like to integrate that with a project running on a different machine, be it across the <a href="http://en.wikipedia.org/wiki/Local_area_network">LAN</a> or <a href="http://en.wikipedia.org/wiki/Wide_Area_Network">WAN</a>. Although it&#8217;s a really swell class you&#8217;ve got, it&#8217;s pretty heavy on CPU usage and requires access to a database that is not available across the network. You can&#8217;t just copy the code on over to your other project, since the resources on that machine are already taxed. Wouldn&#8217;t it be cool if you could just share that class out to that other project and have it act just like a locally installed class? You know, with methods and members.</p>
<p>It is this very thing that SOAP provides. If that wasn&#8217;t cool enough, there&#8217;s one more trick in the hat. SOAP is language agnostic. The server could be running Java and your client code <a href="http://us.php.net/manual/en/function.soap-soapclient-construct.php" title="PHP Manual - Create a SOAP client object">could be in PHP</a>, or <a href="http://us.php.net/manual/en/function.soap-soapserver-construct.php" title="PHP Manual - Create a SOAP Server object" target="_blank">vice versa</a>. This pretty much works between most any object oriented language that has an implementation of SOAP, which is most of the major ones today.</p>
<p>There are also a healthy stack of companies out there providing a variety of data and computation services to developers across the Internet. Things like address look ups, sales tax rates, or stock data. All kinds of data that an individual developer would normally never have access to is now readily embeddable in your code thanks to SOAP.</p>
<p>My point to you here is that just knowing how to access objects your value as a developer shoots up tremendously. Implementing things like the PEAR repository or SOAP isn&#8217;t much different than my little example creating a new Product object.</p>
<h1>Moving Along</h1>
<p>If at this juncture if I haven&#8217;t managed to convince you that there really is some benefits to all this class and object stuff then you might want to stop now while you&#8217;re ahead. Take no shame in this, as I have been there myself many times with various books and tutorials on this subject. More likely my approach to the subject may not have convinced you that there&#8217;s enough benefit to this for the cost of changing how you develop today.</p>
<p>For those of you still with me here, we&#8217;re about to embark into the realm of thinking in terms of object oriented design. Up to this point I&#8217;ve purposely kept things mostly procedural, even the Product class isn&#8217;t much more than some grouped functions.</p>
<p>Actual Object Oriented design gets us thinking in terms of how to better share methodologies between the classes that we create. In OO terms this is referred to as “<a href="http://en.wikipedia.org/wiki/Inheritance_%28computer_science%29" title="Wikipedia article about inheritance">inheritance</a>”. The basic notion is that one class can inherit all the methods and members of another class. The inherited class then gets all those goodies from it&#8217;s parent. From there you can extend or override methods and members of the parent.</p>
<h1>Inheriting A Fortune</h1>
<p>Have I lost you yet? I know this all lost me on the road to OO design many times. To attempt to illustrate this let me present this to you in a purely functional way.</p>
<p>In our pretend scenario we&#8217;ve got a file with a dozen or so functions that deal with presenting different aspects of a product. Most of these are perfect for use across different projects that need to display a product.</p>
<p>A new project from Acme Widgets comes across your desk that could sure use most of that library. Unfortunately 2 of the functions are, by necessity are very specific to the project they are used on. In this scenario they are:</p>
<pre>function showProductSpecs($index)
function displayProductPrice($index)</pre>
<p>On top of this, Acme&#8217;s project also needs a new function that no other project will likely need.</p>
<pre>function generateProductColorDropDown($index)</pre>
<p>To address your problems here you could take all of these functions and put them in a new library specific to the project. Well that&#8217;s not going to work, since older projects expect to find those first two functions in the old library. You can&#8217;t just redefine a function on the fly, and you don&#8217;t want two almost identical versions of your library. How do you track changes to other functions?</p>
<p>You could just rename all the functions to something that&#8217;s specific to the project at hand. That&#8217;s not really all that great either since your function names have already gotten huge to avoid namespace conflicts. When you need all 80 columns for a function name, there&#8217;s a problem!</p>
<p>Darn, wouldn&#8217;t it just be simpler to let us programmers redefine functions on the fly? In short, that would be a really bad thing. Furthermore, I&#8217;m not looking to reinvent PHP here. We&#8217;ve got the tools we&#8217;ve got. And for those of us enterprising folks that are utilizing Object Oriented methodologies none of these problems are a problem at all. In fact, this is the very basis from where we can start into thinking in OO terms.</p>
<p>Let&#8217;s get that Product class back in here with the methods we need to implement. I&#8217;ve removed the accessor methods for clarity and put in those two functions that existed for another project.</p>
<pre>class Product
{
  private $model = “”;
  private $description = “”;</pre>
<pre>  public function __construct($index)
  {
    $this-&gt;pullFromDatabase($index);
  }</pre>
<pre>  public function showProductSpecs($index)
  {
    // Some clever display code
  }</pre>
<pre>  public function displayProductPrice($index)
  {
    // Clever price calculations returned
  }</pre>
<pre>  private function pullFromDatabase($index)
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>So how does this solve the problem of needing new functions for the Acme project? We can now inherit this Product class into a new class called AcmeProduct. Let&#8217;s start slowly here and not implement anything new here.</p>
<pre>class AcmeProduct extends Product
{</pre>
<pre>}</pre>
<pre>$ap = new AcmeProduct(12);</pre>
<p>What the&#8230;? There&#8217;s nothing in that class! How can you create a new object from an empty class for crying out loud? The answer is, of course, inheritance. Everything about the Product class becomes AcmeProduct when you “extend” it.</p>
<p>So what&#8217;s the big deal then? All we&#8217;ve got is two classes that do the exact same thing with a different name. Or so it would seem. How about we add in that special method specific to the Acme project.</p>
<pre>class AcmeProduct extends Product
{
  public function generateProductColorDropDown($index)
  {
    // return some kind of form list
  }
}</pre>
<pre>$ap = new AcmeProduct(12);</pre>
<p>Now we&#8217;ve got everything that Product had, plus a new method only available to code that creates a new AcmeProduct. We&#8217;ve just added functionality to the Product class without having to alter anything in the Product class.</p>
<p>Now let&#8217;s override those functions in the Product class that need something special for this Acme project.</p>
<pre>class AcmeProduct extends Product
{
  public function generateProductColorDropDown($index)
  {
    // return some kind of form list
  }</pre>
<pre>  public function showProductSpecs($index)
  {
    // Specs like Acme wants to see
  }</pre>
<pre>  public function displayProductPrice($index)
  {
    // Pricing just for Acme
  }
}</pre>
<pre>$ap = new AcmeProduct(12);</pre>
<p>Unlike functions in the global namespace, methods can be redefined by a child class that&#8217;s inherited them. We get all the other methods and members from the Product class as though you had copied and pasted them on in. We&#8217;ve added to the library of methods, and changed 2 of them. All the while we haven&#8217;t had to alter a single line of code in the original Product class. Can you dig it?</p>
<p>Code that had been utilizing that Product class all along will not be impacted in the least by this new class.</p>
<h1>Inheritance Implications</h1>
<p>Dear reader I need you to stop for just a moment and consider the implications of this. If you think of this in procedural terms, we&#8217;ve just refined an otherwise generic library of functions into a more specific library without losing anything of the original.</p>
<p>If you were to go back and optimize some of your other methods in Product, any class that inherits from this gets all those benefits as well. You may well find that you never actually create an object from that Product class directly, but instead extend it to new classes that refine what it does for each new project. Along that line of thinking, you would try to stuff all those methods and members that child classes could all use into that Product class.</p>
<p>PHP restricts your ability to inherit to just one parent. In other words, a class can only extend from one parent. There&#8217;s a darn good reason for this, which I won&#8217;t get into here. Just remember that only one parent is allowed. Thing is, you can have multiple generations of parents going up an object&#8217;s family tree. For example, here are three classes that live in the same inheritance tree:</p>
<p>Product &gt; AcmeProduct &gt; AcmeProductWidgets</p>
<p>In this case, AcmeProductWidgets gets everything that AcmeProduct has to offer, which is also everything Product has as well.</p>
<p>Where a child is restricted to one parent, a parent can have lots of little class kiddies running about.</p>
<p>Product    &gt; AcmeProduct<br />
&#8230; &gt; CompProduct<br />
&#8230; &gt; SurfProduct</p>
<p>The top most parent in the tree would contain the methods and members most likely needed by it&#8217;s children. Then each child further refines or adds functionality.</p>
<h1>I Miss My Parent</h1>
<p>Our AcmeProduct class has thus far just replaced two perfectly good methods from it&#8217;s parent class. In doing so we had to use that evil “Copy&amp;Paste” coding method. What if what you really wanted to do with one of these methods was to just refine it just a bit. Let the parent class do all the work, then just tweak things a bit and take all the credit. Here&#8217;s the code:</p>
<pre>class AcmeProduct extends Product
{
  public function generateProductColorDropDown($index)
  {
    // return some kind of form list
  }</pre>
<pre>  public function showProductSpecs($index)
  {
    // Get the initial results from the parent method
    $specs = parent::showProductSpecs($index);
    // Now refine it in some way and return it
    return $specs;
  }</pre>
<pre>  public function displayProductPrice($index)
  {
    // Pricing just for Acme
  }
}</pre>
<p>Worked in a new one in there for you, “parent”. Using parent with our fancy Name Space Identifier double colon thingy, we can get mom (might be dad) to do all the hard work for us. Since both parent and child have this method with the exact same name you have to have some way of telling PHP which one you mean. Using the keyword &#8220;parent&#8221; does that very thing.</p>
<h1>Are My Parents Keeping Secrets</h1>
<p>Child classes can&#8217;t directly access either methods or members that have been marked “private”. Earlier when I stated that a child gets everything that the parent provides, what this really means is what it provides that isn&#8217;t private.</p>
<p>Along the same line of thinking as when I first presented the notion of setting permissions for methods and members, this all holds true even for child classes. There are just some things that parents don&#8217;t want their children to know about.</p>
<p>The notion of inheritance brings up a third kind of permission that only makes sense when you will be extending an object. Instead of public or private, you can set a permission of “protected”.</p>
<ul>
<li>A method or member that is set to “protected” may only be accessed within the same or inherited class.</li>
</ul>
<p>Let&#8217;s see this in action with our now heavily abused Product class.</p>
<pre>class Product
{
  private $model = “”;
  private $description = “”;
  protected $index = 0;</pre>
<pre>  public function __construct($index)
  {
    $this-&gt;index = $index;
    $this-&gt;pullFromDatabase();
  }</pre>
<pre>  public function showProductSpecs()
  {
    // Some clever display code
  }</pre>
<pre>  public function displayProductPrice()
  {
    // Clever price calculations returned
  }</pre>
<pre>  protected function fetchPrice()
  {
    // Do something database'ish to get the raw product price
  }</pre>
<pre>  private function pullFromDatabase()
  {
    // Fancy database query would run here
    $this-&gt;$model       = $dataRow[“model”];
    $this-&gt;$description = $dataRow[“description”];
  }
}</pre>
<p>I&#8217;ve changed 2 things in here. Before we get into the permissions bit, notice how I&#8217;ve changed the constructor. It now sets a member variable called $index then calls to the database pull. In doing so, I now no longer need to send that argument along to each and every method, as any of these methods can look up $this-&gt;index to get the value.</p>
<p>Both the fetchPrice() method and the $index member are protected. So, if you were to try the following bit of code, expect failure in your future.</p>
<pre>$p = new Product(12);
$price = $p-&gt;fetchPrice(); // Don't have permissions to do that here!</pre>
<p>However, the following is perfectly okay to do.  In fact, this is what setting that “protected” permission is all about.</p>
<pre>class AcmeProduct extends Product
{
  public function generateProductColorDropDown()
  {
    // return some kind of form list
  }</pre>
<pre>  public function showProductSpecs()
  {
    // Get the initial results from the parent method
    $specs = parent::showProductSpecs();
    // Now refine it in some way and return it
    return $specs;
  }</pre>
<pre>  public function displayProductPrice()
  {
    $price = $this-&gt;fetchPrice();
    // Pricing just for Acme
    return $acmePrice;
  }
}</pre>
<p>The public method displayProductPrice() now calls a protected method from the parent as though it were a method within this very same class. We don&#8217;t use the “parent” identifier in this case since we don&#8217;t have to resolve a naming conflict like when you override a method.</p>
<h1>Getting Abstract</h1>
<p>Earlier I suggested the notion that a class at the top of the tree might be more useful as a container for methods and members to be shared by child classes. What if you wanted to enforce this. Say you wanted to make sure nobody ever tried to create a new Product object. You only want inherited children to use that class, then folks would create objects from there. Simple enough. Just state that the class is “<a href="http://us.php.net/manual/en/language.oop5.abstract.php" title="PHP Manual - Class Abstraction">Abstract</a>”.</p>
<pre>abstract class Product
{
  ....
}</pre>
<p>With that in place, you can inherit everything provided by the Product class, you just can&#8217;t directly create an object from it. In this case, it would make a lot of sense to do this with a nice generic class like Product, with the thinking being that you only want more refined code actually getting utilized as objects.</p>
<p>Abstraction also allows you to force children to take care of some chores on their own. By defining a method without a body you are saying that a child must implement that method in order to inherit from this class. You know you&#8217;ve heard mom or dad say, &#8220;do as I say, not as I do&#8221;.  This looks like:</p>
<pre>abstract class Product
{
  public function childMustDo();
  ....
}</pre>
<p>Why on earth would you want to do something like that? For this article I&#8217;m going to dodge that question, as it gets into the notion of an object contract as well as polymorphism. A couple of topics going beyond the scope of what I&#8217;m presenting at this time.</p>
<p>I should also mention here that if any method within a class is abstract, in that it doesn&#8217;t have a body, then the entire class must be marked abstract. Making the class abstract does not require you to have any abstract methods though.</p>
<h1>When An Object Doesn&#8217;t Want Children</h1>
<p>In the case of our Product class, child classes really made a lot of sense. In some cases not only do children not make sense, but you actually want to enforce the notion that the class in question can not be inherited from. Mark that class “<a href="http://us.php.net/manual/en/language.oop5.final.php" title="PHP Manual - Final keyword" target="_blank">final</a>” and no more inheritance is possible.</p>
<pre>final class Product
{
  ....
}</pre>
<p>That&#8217;s all well and good, except that we know this Product class is something we want to extend. If the case is that we just want to have certain methods that cannot be overridden by a child class, you can modify just that method with “final”.</p>
<pre>class Product
{
  final public function neverToBeOveridden()
  {
    // perfectly formed code goes here
  }
  ....
}</pre>
<p>Note that marking a method as private does not prevent a child class from overriding it. A private method just isn&#8217;t visible at all to anything outside of the class that declares it. Normally you would be better off avoiding overriding private methods due to the increased ambiguity. Be explicit in all that you do, and code will be usable and reusable for years to come.</p>
<h1>What Got Left Out</h1>
<p>I don&#8217;t want this to be the final word on Object Oriented design for you. My intention here was to help you with jumping some of the conceptual hurdles in going from a procedural methodology to an Object Oriented strategy. So as to keep you around to this point I&#8217;ve left a few concepts out of here so as to leave them to more qualified authors to address.</p>
<ul>
<li>I&#8217;ve totally dodged out of talking about Interfaces.  They&#8217;re important, but not for the initial understanding of OO design.</li>
<li>When do you inherit and when do you include objects?  This gets into the realm of “IS A” and “HAS A” relationships.</li>
<li>Various best practices and design patterns were all but totally vacant.  Too many good books out there on these topics.</li>
<li>There are several more magic methods I didn&#8217;t discuss. The two I did talk about I believe are the ones that are utilized far more often than any others. Some of these methods aren&#8217;t especially wise to use, which is why I didn&#8217;t bring up stuff like the Overloading methods.</li>
<li>Class autoloading got left out.  It&#8217;s a simple enough concept to read about in the official PHP manual.</li>
<li>Static and constant data member variables.</li>
<li>The extremely important topic of exception handling got left out.</li>
<li>Lots of implementation details that are better handled elsewhere.</li>
</ul>
<h1>Summary</h1>
<p>Even with a lot of the details left out I hope I have presented to you a reasonable introduction into the world of Object Oriented design. More importantly, if you can begin to see how you can utilize these concepts into your next project, or perhaps revamp an already existing project, I would consider this a success.</p>
<p>In a language like PHP the notion of traditional functions doesn&#8217;t go away now that PHP 5 has brought to us some real OO tools. Try not to get lost into the notion of either OO or procedural methods as the one true path. Combining the two is where you get the most bang for your efforts. Knowing when to apply one strategy or the other is a matter of experience and study.</p>
<h1>Further Reading</h1>
<p>There are a lot of new books coming out that get into the Object Oriented functionality in PHP. From what I&#8217;ve seen, many of these are garbage. Some are not much more than barely updated versions of previous PHP 4 books that just barely touch on how dramatic a change PHP 5 has brought to us lowly web developers. Here are a few good ones I feel comfortable in recommending.</p>
<p><i>“<a href="http://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208/" title="Buy it on Amazon" target="_blank">Head First Java</a>”</i><br />
by: Kathy Sierra &amp; Bert Bates<br />
O&#8217;Reilly</p>
<p>A Java book to learn about PHP? You betcha. If there are some awful PHP books out there, that number is easily tripled when talking about Java books. Here is an exception. This is a wonderful introduction into Java and Object Oriented design. The biggest mental translation to make here is that PHP is not a type safe language, where as Java requires that you declare everything explicitly. Beyond that, the Object Oriented discussions mostly apply to any OO capable language.</p>
<p><i>“<a href="http://www.amazon.com/Object-Oriented-PHP-Concepts-Techniques-Code/dp/1593270771/" target="_blank" title="Buy it on Amazon">Object-Oriented PHP</a>”</i><br />
by: Peter Lavin<br />
No Starch Press</p>
<p>Although I found this author&#8217;s approach to be weak in how he introduces OO design, it&#8217;s an outstanding follow up to better understanding the specifics of how PHP 5 handles things. Just keep in mind that his first couple of chapters has examples using PHP 4. The remainder of the book is pure PHP 5.</p>
<p><i>“<a href="http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/" title="Buy it on Amazon">PHP Objects, Patterns, and Practice</a>”</i><br />
by: Matt Zendra<br />
Apress</p>
<p>Once you have what you think is a firm handle on what all is going on with OO design it would be about time to give some time over to this book. Here is where you&#8217;ll pick up many of the best of PHP&#8217;s best practices.</p>
<h1>Is It All Worth It</h1>
<p>For just the sake of PHP developing, it&#8217;s worth it and then some. The more that you utilize this approach to designing software, the more time you&#8217;ll save. You&#8217;ll find it far easier to pass code around to various projects, even projects you may never be directly involved with. You can now utilize the rich variety of classes available on the Internet, and extend them as needed.</p>
<p>Perhaps even more importantly, other languages like Java, Python, and even C++ start making a lot more sense. Most OO design techniques cross the language barrier with mostly syntax details changing between them. There&#8217;s certainly more than just minor syntax details that divide these languages, but my point is that the concepts cross those barriers. This is one of the reasons why something like SOAP is able to work at all. The object concept bridges across the divide.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/metrol.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/metrol.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metrol.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metrol.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metrol.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metrol.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metrol.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metrol.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metrol.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metrol.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metrol.wordpress.com&amp;blog=2243644&amp;post=10&amp;subd=metrol&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metrol.wordpress.com/2008/03/08/php-from-procedural-to-object-oriented/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a26c380e3f4214e0f4e501b5a1dfa5ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">metrol</media:title>
		</media:content>
	</item>
	</channel>
</rss>
