Page 1 of 1

User Submitted Tutorial: About the Classes

Posted: Sat May 17, 2003 9:44 pm
by evilcoder
Howdy People.. Well a tutorial hasn't been written for a while, so i thought i'd spend some of the 8 hours i have writing one for you.. The focus of this tutorial will be on establishing Classes and how they can be used, i will be creating a class which i believe will and can be of use to anyone here.

The Stucture of a Class:

Code: Select all

 
 
<?php 
 
class ClassName 
{ 
   // Define Class Variables 
   var $Foo; 
   var $Bar; 
 
   /* A function which has the same name as the class is known as the constructor, and gives values to the class variables. */ 
 
   function ClassName() 
   { 
      $this->Foo = $Value1; 
      $this->Bar = $Value2; 
   } 
 
   /* In between the Brackets () are what are known as Parameters, in this instance they are $Foo and $Bar */ 
 
   function FooBar( $Foo , $Bar ) 
   { 
      echo "\$Foo is equal to: " . $Foo . " and \$Bar is equal to: " . $Bar . "; 
   } 
} 
 
?> 
 
 
 
 
That is the structure of most classes, but what are classes?

A class is nothing but a collection of functions which perform a specific task (also called Objects). Each Class can be defined (used) more times on the same page (have multiple instances). And, finally, every class has its own methods (functions) to be then called from within a page.

It's also important to realise that Classes are not just a set of functions, but can be given a set of Global Variables, which is the defining factor between just a file or functions and a class.

Why use classes?

This is a common question and luckily there is a simple answer. You Dont have to, but when you are developing sites that have lots of repetitive code, then Classes can make your life so much simpler. I will demonstrate this in more detail as the article progresses and we start cooking.

Learning in Action

I find the only way to learn something is to work while reading about it. That's why i'm going to run through a class which i'm sure will be useful for those out there that use multiple databases in their site.

The Database Class

OK, now we will start off by creating a file called: Database.class.php

Once that is created we can now start building your class. Start by initiating your php tags, and creating the class called, Database.

Code: Select all

 
<?php 
 
class Database 
{ 
 
 
Now that, that's done, we can define the class variables.

Code: Select all

 
 
   var $DatabaseHost; 
   var $DatabaseUser; 
   var $DatabasePass; 
   var $DatabaseName; 
 
 
I'll run you through what these variables will be, although they are pretty self explanitory:

$DatabaseHost = Your Host server (eg. localhost, for many)
$DatabaseUser = Database Username
$DatabasePass = Password for the Username
$DatabaseName = Name of the Database.

It's now time to create the constructor for the Database class.

Code: Select all

 
 
   function Database() 
   { 
      $this->DatabaseHost = NOT_SET; 
      $this->DatabaseUser = NOT_SET; 
      $this->DatabasePass = NOT_SET; 
      $this->DatabaseName = NOT_SET; 
   } 
 
 
The constructor has now been built and all the variables have been assigned the value NOT_SET, in other words, nothing. Now, we can start building the goof stuff.

If your wondering what the $this-> is i'll tell you. $this-> is a way to call variables or functions from within a class.

Lets build the DBConnect function:

Code: Select all

 
 
   function DBConnect( $DatabaseHost , $DatabaseUser, $DatabasePass , $DatabaseName ) 
   { 
      $ServerConnection = mysql_pconnect( $DatabaseHost , $DatabaseUser , $DatabasePass ); 
      
      if ( !$ServerConnection ) 
      { 
         echo( "Sorry, but a connection to the server could not be made " . mysql_error() ); 
      } 
      
      $DatabaseConnection = mysql_select_db( $DatabaseName , $ServerConnection ); 
 
      if ( !$DatabaseConnection ) 
      { 
         echo( "Sorry, but a connection to the datavase could not be made " . mysql_error() ); 
      } 
   } 
 
 
Now the connection function has been made, we can make the close function.

Code: Select all

 
 
   function DBClose() 
   { 
      mysql_close(); 
   } 
 
 
That was simple. Finally, we can close off the class and start on how this can be used.

Code: Select all

 
 
} 
 
?> 
 
 
Now we have our class called Database. But at the moment its not doing anything, and will continue to do nothing until it is called. So lets call it.

In order to use the function of the class you will need to create a new instance of the class and also include the Database.class.php file into your page. So where you want to create a database connection you would initiate the class like so:

Code: Select all

 
 
require( "Database.class.php" ); 
$Database = new Database; 
 
 
Then you can call the DBConnect() function and define the database variables inside.

Code: Select all

 
 
$Database->DBConnect( "localhost" , "username" , "password" , "mydatabase" ); 
 
 
This code now gives the variables inside the function values. Now, commonly people dont like putting raw data into pages, and like to define passwords and the like in other files, that can still be done, just include the page with your values and add the variables where i have put the raw values.

OK, now once you've done all your SQL code, you can close the database like so:

Code: Select all

 
 
$Database->DBClose(); 
 
 
Well, i'm not sure whether this is helpful, but i hope it sheds a bit of previously unseen light on the class issue.

Posted: Sat May 17, 2003 9:56 pm
by McGruff
Maybe you just posted this as a simple tutorial example but the idea of a database connection class has always puzzled me.

Would it not be simpler (and more efficient) to define some constants in a config section, and just use the normal php functions? Saves the overhead of a class and several user-defined functions.

If you have a need to support several databases OK I could see the point. Even then, I would probably prefer to recode per install to create more efficient code - unless you are distributing a php program (phpNuke eg) where you won't be installing it for clients and can't assume they will be able to recode it themselves.

Posted: Sat May 17, 2003 10:00 pm
by evilcoder
I know its not the most useful example, but it was merely to show how Classes are constructed, and how they COULD be used.

Posted: Sat May 17, 2003 10:09 pm
by McGruff
oops :oops:

Posted: Sat May 17, 2003 10:12 pm
by jason
Using classes for database connections can assist in several ways.

First, I use the Eclipse Library for PHP and it's Database library code. For me, connecting to a database is simple:

Code: Select all

<?php
 
$db = new MyDatabase("database_name", "host");
$db->connect("username", "password");
 
?>
The benefit comes in when you have to work with queries, and results.

Code: Select all

<?php
 
$result =& $db->query("SELECT * FROM table");
if ( $result->isSuccess() ) {
    $it = new QueryIterator($result);
    while ( $it->next() ) {
        $row = $it->getCurrent();
        print_r($row);
    }
}
 
?>
I can use that same format no matter what database I use. It's a single interface. This gets even easier if I am using the Phrasebook pattern to manage my SQL queries.

Code: Select all

<?php
 
$result =& $db->query(pbGet('TABLE_SELECT'));
if ( $result->isSuccess() ) {
    $it = new QueryIterator($result);
    while ( $it->next() ) {
        $row = $it->getCurrent();
        print_r($row);
    }
}
 
?>
Working with transactions is just as easy.

Code: Select all

<?php
 
$trans =& $db->createTransaction();
$trans->start();
$trans->query(pbGet('TABLE_INPUT', $data_array));
$trans->query(pbGet('TABLE2_UPDATE', $data_array));
$trans->query(pbGet('TABLE3_UPDATE', $data_array2));
$trans->query(pbGet('TABLE4_UPDATE', $data_array2));
if ( $trans->isSuccess() ) {
    $trans->commit();
} else {
    $trans->rollback();
}
 
?>
This also makes working with multiple return queries easy as well:

Code: Select all

<?php
 
$selectResult =& $db->query(pbGet('TABLE_SELECT'));
$selectAnotherResult =& $db->query(pbGet('TABLE_SELECT'));
$selectMoreResults =& $db->query(pbGet('TABLE_SELECT'));
 
/*
    From here, I can work with three seperate result sets
    with ease.
*/
 
?>
Hopefully, this will help a bit more.

Posted: Sun May 18, 2003 6:47 am
by riley
In addition to the common naming of methods and properties while using multiple database manufacturers (Mysql, sybase, oracle, sql, odbc). I also have information available about the returned data ( field names, field size, autoid, etc.). I don't always use it, but it has no visible effects on performance. It is quit nice to add, edit, or delete functionality and not have to dive into each different file to make adjustment to code.

tutorial for classes with database connections as example

Posted: Mon May 19, 2003 9:33 am
by wim
Dears,

It might be useful to invest a little time in the DB extension under Pear which will be a class-driven connector to a variety of databases.

Posted: Wed May 21, 2003 10:23 am
by Zoram
Hey jason, what is it that your $db->query() function is returning? i was trying to make something like that work where it returns the result and it wasn't working for me.

Posted: Wed May 21, 2003 2:26 pm
by jason
Zoram wrote:Hey jason, what is it that your $db->query() function is returning? i was trying to make something like that work where it returns the result and it wasn't working for me.
Documentation for the Eclipse Lib can be found here:

http://www.students.cs.uu.nl/people/voo ... index.html

wim: Having worked with DB in PEAR, I can say I am very happy to be using Eclipse. Much better, IMO.

Posted: Sun Jun 15, 2003 11:39 am
by nielsene
Hey jason can you provide more information on the Phrasebook pattern you reference? I think I've been implementing something similar and would like to avoid it if there a good solution out there... Web-searchers are turning up very minimal classes that wouldn't be useful.

Posted: Sun Jun 22, 2003 4:42 pm
by nielsene
OK, I finally found some keywords that helped with googling for phrasebook and ended up at one of jason's blog entries. Interesting reading at the linked PDF. Any chance you might make your PHP implementation of the pattern availible for others?

Posted: Wed Apr 11, 2007 11:43 am
by Theory?
Isn't the constructor a magic method, __construct()? I thought naming the constructor after the class was PHP4.

Posted: Wed Apr 11, 2007 11:47 am
by feyd
Theory? wrote:Isn't the constructor a magic method, __construct()? I thought naming the constructor after the class was PHP4.
PHP 5 supports both, but it will error if both exist. I don't recall offhand what 6 supports.

It should also be noted that this thread is quite old.