[Sussex] Simple OOP tutorial

Nicholas Butler nik at reducedhackers.com
Fri Aug 27 09:52:41 UTC 2004


Thats wierd, since I recently wrote a few notes to myself whilst 
reviewing PHP classes.

Heres the notes...

2004 08 10 Playing with Classes

The wonderful thing about class based programming is that it can lead to 
wards functional and reusable code to be quickly  implemented. In order 
to experiment with classes in PHP I need a project and for this I will 
be aiming to build two classes.   Since in my experience of PHP has to 
date involved the use ( and abuse ) of the function I would rather build 
a more cohesive application oject that will not fall foul of the 
vaguerities of functions and GLOBAL declarations.

One class will enable the reading of a standard Configuration File. The 
other class will enable me to subclass mysql into generic function calls 
such as insert/update etc etc etc



Now Im a VB school of Class developer, so lets review what I remember 
about classes

The class can contain constants which can be defined ( and possibly 
overridden ) within the Class.
The class when initialised can have a initialise ( or constructor event 
) wherein certain functions can be called .
the class can have a number of Properties, where in values can be set 
into or gotten out of the class
the class can have an event which can occur as part of a 
function(constructor) and can be reacted upon ..


PHP can support the following

The class can contain constants which can be defined ( and possibly 
overridden ) within the Class.
The class when initialised can have a initialise ( or constructor event 
) wherein certain functions can be called .
the class can have a number of Properties, where in values can be set 
into or gotten out of the class
... okay I really miss EVENTS ... then again its really only useful in a 
Dynamic Synchronous environment.


Lets start with a configuration file, one line per item, tab seperated. 
with setting and value


--file : configuration
dbDatabase      exampled
dbUserName      aSecretUser
dbPassword      itsASecr3t
dbHostname      localhost



So now lets create the settings.class to read it .

---file : settings.class

<?
class settings{
        var $configFILENAME = "configuration";
    var $setting ;
function settings(){
     // on initialisation grab configuration and read it.
     $handle = fopen($this->configFILENAME, "r");
     $this->setting = array();
     while (!feof($handle)) {
     list($key,$value) = explode("\t",fgets($handle, 4096));
     $this->setting[$key] = $value;
     }
     fclose($handle);
     }

function setting( $key ){
     return $this->setting[$key];
     }
function settingCount(){
     return (count($this->setting)-1);
     }

}
?>


.. Notice that the Class Settings contains a function settings() .. this 
effectively creates the Class Instantiator event which says, when a new 
Class Object is created, do this function. Which helps to initialise the 
class.


so to test, lets create a test_settings.php file.

-- file test_settings.php
<?
include  "settings.class";

$config = &New settings;
$count = $config->settingCount();
$result = $config->setting('dbDatabase');

echo "The Settings count of the Configuration file is <BR>";
echo "Count  $count <HR> Result $result ";

?>


and the out put is..
The Settings count of the Configuration file is <br>Count  4 <hr> Result 
exampled


okay .. so now lets use this to correctly extend a MySql object.


--file database.class

<?
class dataBase extends settings{
        var $dbDatabase;
        var $dbUserName;
        var $dbPassword;
        var $dbHostname;

        var $connection;

        var $sqlStatement;

        var $result;
        var $row;

        function dataBase(){
                //class initialise grab variables of scope from settings 
file.
                parent::settings();
                $dbDatabase = $this->setting('dbDatabase');
                $dbUserName = $this->setting('dbUserName');
                $dbPassword = $this->setting('dbPassword');
                $dbHostname = $this->setting('dbHostname');
                $this->connection = mysql_connect($dbHostname, 
$dbUserName, $dbPassword) or die("Unable to connect to database server, 
$dbHostname $dbUserName , $dbPassword .");
                 mysql_select_db($dbDatabase, $this->connection) or 
die("Unable to select desired database. [ $dbDatabase  $dbHostname 
$dbUserName , $dbPassword ] ");
                }

        function queryString($strSQL){
                $this->sqlStatement = $strSQL;
                }

        function connect(){
                
$this->result=mysql_query($this->sqlStatement,$this->connection) or die 
("Unable to Run Query " . $this->$sqlStatement);
                }
        function execute($sql){
                $tmpresult = mysql_query($sql,$this->connection) or die 
("Unable to Run Query " . $sql);
                }

        function row(){
                $this->row = mysql_fetch_array($this->result);
                return $this->row;
                }

        function fieldName($key){
                return mysql_field_name($this->result,$key);
                }

        function fields(){
                return mysql_num_fields($this->result);
                }

        function field($key){
                return mysql_fetch_field($this->result,$key);
                }

        function field($key){
                return mysql_fetch_field($this->result,$key);
                }
}
?>


The Class uses the parent::settings(); constructor call to initialise 
the settings object within the database class. To call this object we 
simply need to


Create a new page called test_mysql.php and call the classes, for example

<?
include  "settings.class";
include  "database.class";

$sql = "select * from bears";

$db = &New dataBase;
$db->queryString($sql);
$db->connect();


//Demonstrate Field Iteration.
echo "The Database has " . $db->fields() . " fields and they are named 
as follows <BR>";
for($i=0;$i<$db->fields();$i++){
        echo "Fields $i is " . $db->fieldname($i) . "<BR>";

        }

// Demonstrate row Iteration.

while($row = $db->row() ){
        echo $row[1] . "<HR>";

}

?>


which makes the following output
The Database has 3 fields and they are named as follows
Fields 0 is recordno
Fields 1 is bearname
Fields 2 is createdate
BrownieClaireToniRoger



Having built the database class we can now create the table class.. to make
life easier to simply display table results as follows.

--file table.class
<?
class table extends dataBase{
        var $style ;

        function table(){
                //class initialise grab variables of scope from settings 
file.
                parent::dataBase();
                }
        function tableBegin(){
                return "<TABLE>";
                }
        function tableEnd(){
                return "<TABLE>";
                }
        function header(){
                $tmp = "<TR class=$style>";
                for($i=0;$i<$this->fieldCount;$i++){ $tmp.="<TD 
class=$style >" . $this->fieldName[$i]  ."</TD>";}
                $tmp.= "</TR>";
                return $tmp;
        }
        function tableRows(){
                $tmp="";
                while($row = $this->row()){;
                $tmp .= "<TR class=$style>";
                for($i=0;$i<$this->fieldCount;$i++){ $tmp.="<TD 
class=$style >" . $row[$i]  ."</TD>";}
                $tmp.= "</TR>";
                }
                return $tmp;

        }
}
?>


Now having built that lets build the test_table.php

<?
include  "settings.class";
include  "database.class";
include  "table.class";

$sql = "select * from bears";

$table = &New table;
$table->queryString($sql);
$table->connect();

//demonstrate Header displays
echo $table->tableBegin();
echo $table->header();
echo $table->tableRows();
echo $table->tableEnd();
?>


which outputs


recordno    bearname    createdate
1        Brownie        2004-06-17
2        Claire        2004-08-09
3        Toni        2004-08-09
4        Roger        2004-08-09




Now ... this leads to a question about building a Class to represent a 
Query/table within a Database and to use this to extend a object such as 
a Bear, Invoice, Shopping Item etc etc etc ... but thats for another topic.









More information about the Sussex mailing list