phpHoo, Part I | 6 | WebReference

phpHoo, Part I | 6

phpHoo, Part I

Enter PHP

PHP is an embedded scripting language similar to ASP in that the programs are written as HTML pages. The code in the page is executed along with any HTML parsing. One of PHP's major strengths is it's ability to easily integrate with many different SQL servers. The most popular pairing is PHP+MySQL. The other major advantage of PHP is that it was specifically designed from the ground up to work on the Web. Remember, this program was developed to match perlHoo part I in less than 3 hours? This is because PHP makes it very easy to work on the web, as you're about to see.

Classes and Object Oriented Programming

The Class, as defined in most object oriented languages, is a mechanism by which a programmer expresses the design and manipulation of a custom data type. In this case, the data type our class describes and manipulates is our phpHoo database. The Class's combined variables and methods, is known as an Object. The concepts behind Object Oriented programming can get very confusing for new programmers, so let's give a real world analogy to OOP.

The next time you walk into a video store, start thinking of it as a giant sized Object. The store is a living, breathing, thinking thing. The store knows about every video sitting on it's shelves. It knows when new releases are going to be placed on a shelf. It knows what movies are available, which ones have been checked out, and when they're due back. All of the employees in this "Video Store Object" are actually methods and functions used to manipulate the store's videos and sales. (It's data) There's an employee that opens (Creates) the store in the morning. (The Object's "Constructor Method"). There are employees that restock the shelves, employees that handle checking out a video, inventory, receiving new video shipments - every method required to keep the "Object" functioning properly.

As the programmer (Customer) that accesses this Object, you could care less -how- it does any of this. You only care about the "public" methods available to you as the user of this Object. You can ask an employee (method) if a video is available, and that employee will answer your question. You don't care how the employee obtains the answer to your question. You don't care if it has to look up the video in the database, or if it already knows the answer. This is "abstraction". The beauty of abstraction is that it saves the programmer from having to know anything at all about the inner workings of the "video store class". As we all know, there are thousands of video stores out there... but the "Object" is always the same! The Object has a different name, thousands of completely different videos (data), but guess what?

The methods you use on the "Video Store" object are always the same!

This get's better though, since this same "Object" can be used on any store! Grocery Stores, Clothing stores, automotive stores, it doesn't matter. The data changes, the location changes, the name changes, but we can use the same Object to work with any of these stores. There's always some guy that shows up at dawn and opens the store. There are always employees stocking the shelves and maintaining inventory and there are always employees answering questions from annoying programmers. The true power of Object Oriented programming is it's ability to adapt. The same Class used to create and maintain the Video Store is the same Class used to create and maintain the Chevy dealership on the corner. This is why Object Oriented programming has taken the programming community by storm. The ability to re-use the same "object" over and over again, the ability to have multiple independent copies of the same object at the same time, all without writing a single additional line of code, is programming nirvana.

The first thing we'll need to do in our phpHoo program is to create the database routines PHP will use to manipulate the data in our database. I decided to encapsulate all of the MySQL access for this tutorial into a Class file. Class files are similar in concept to perl Modules like the CGI.pm perl module. They are an easy way of organizing functions that deal with the same data. We're going to create a PHP class to handle the majority of the MySQL data.

Lines 3 thru 11 of mysql.php3 create the initial Class definition, and set up a few global variables. The four variables you'll need to work with are DBASE, USER, PASS, and SERVER. DBASE is the name of the database we'll be working with. (phpHoo). The USER and PASS variables should contain your database username and password respectively. The SERVER variable contains the method used to connect to the MySQL server. If the web server and the MySQL server are being handled on the same machine, it'll be set to 'localhost'. If however the MySQL server is hosted by a different machine, you'll need to specify that hostname in the SERVER definition. Once you've finished defining these 4 variables, we're done with the configuration of phpHoo! No paths, no file specifications, this is it.

Lines 10 and 11 and 13 set up some more "global" variables in this Class, TRAIL, HITS, and AUTOAPPROVE. Lines 15 through 21 is our first "method" in the class. The error() method is an ultra-simplistic error routine. If we encounter an error anywhere in this Class we'll call this method to output the error message and exit the program, so obviously we're only going to call this method if something truly catastrophic occurs.

The init() method on lines 23 through 37 is the first method we'll call in the MySQL Class. Lines 25 through 28 grab the global variables USER, PASS, SERVER, and DBASE. Pay particular attention to the way we obtain these values.

Line 25: $user = $this->USER;

Before we continue with the program, let's talk a bit about Object Oriented Programming (OOP), and how it applies to PHP. If you're not familiar with Object Oriented Programming, please stop here and take a look at the SIDEBAR.

All functions in PHP, as in most structured languages, are self-contained. The variables a function manipulates exist only within that function. This is called "Variable Scope". Here's a very quick example of this:

function tweak_Vals($a,$b)
{
    echo "
\nFunction Start
\n"; echo "A equals [$a], B equals [$b]
\n"; $a = $a + $b; $a = $a * $a; $b = $a - $b; echo "A now equals [$a], B is now [$b]
\n"; return $a; } $a = 2.2; $b = 5.0; tweak_Vals($a,$b); echo "Function Returned

\n"; echo "But A is still [$a] and B is still [$b]
\n"; echo "Now if we make an assignment...
\n"; $a = tweak_Vals($a,$b); echo "A becomes [$a] yet B is still [$b]
\n";

When this program runs, it outputs the following:

    ------------------------------------
    Function Start 
    A equals [2.2], B equals [5] 
    A now equals [51.84], B is now [46.84]
    Function Returned
    
    But A is still [2.2] and B is still [5] 
    Now if we make an assignment...
    
    Function Start 
    A equals [2.2], B equals [5] 
    A now equals [51.84], B is now [46.84]
    
    Function Returned
    
    A becomes [51.84] yet B is still [5] 
    ------------------------------------

As you can see, functions work on the values they are given or obtain, but do not make changes to those variables outside of the function's "scope" unless we force it to. This is a MAJOR difference between PHP and Perl. In Perl, variable scope is optional. In PHP, it's mandatory.

[ Side note: Notice what PHP did with the float value '$b', which was set to '5.0'. PHP will quietly and automatically make type conversions like this on an as-needed basis. Since integer math is always faster than floating point math, PHP converts a value to an integer whenever it can get away with it. Although we assigned $b to '5.0', a floating point decimal value, PHP recognized it as a true integer and treated it as such until decimal math was required (in the function). ]

Since we want the "USER", "PASS", and other global variables to be available at all times, we define them as global with the 'var $VARIABLE' construct at the beginning of the class. However, since each function is autonomous, we need to tell the function where to get at those global variables. In PHP, the keyword used to describe the "current instance of this class" is the '$this' construct. '$this->USER' tells PHP that the variable exists within this instance of the class and is otherwise self-contained. '$this' can also point to other methods within the class. Be sure to keep this in mind (pun intended) when writing your function names and variable names to avoid conflicts.

'$this->method-name()' is used to have one method within an instance of the class access another method within the same instance. (If you just got hopelessly confused, it's time to stop here and go read the SIDEBAR. One method accessing another method is analogous to one employee asking another where a video is within the store).

The init() method grabs the global variables and gives them local scope on lines 25 through 28. We can use PHP to open a connection to the database on line 30 using these values. If the mysql_connect() function succeeds, it returns a positive integer value which we assign to '$conn'. '$conn' is going to be our "Connection Identifier". All future calls to the MySQL database require this Connection Identifier. If the connection fails, it returns a "false" value and the error() method is called. The error() method on lines 15 through 21 assemble a human-readable error message and prints it out to the client (web browser). Since we only plan on calling the error() method if something truly catastrophic occurs, this method will exit the program if it's called.

If the mysql_connect is successful, we use the mysql_select_db() method to tell PHP which database on the MySQL server to use. Notice that the method requires our connection identifier? This is why the lack of a connection identifier is considered a fatal error. Everything in our program from this point on requires the database and if it's not there, there's no point in continuing with the program is there? The mysql_select_db() method returns TRUE upon success and FALSE upon failure, and if it returns false, it's considered a fatal error and the program exists with the error message "Dbase Select failed", along with the exact error number and mysql error message. If everything is successful in the init() method, we assign the global variable $CONN to hold our Connection Identifier and return a true value from the method.


http://www.internet.com

Produced by Jonathan Eisenzopf and
Created: July 20, 1999
Revised: July 20, 1999

URL: http://www.webreference.com/perl/xhoo/php1/