PHP classes

Creating a php class is a good way to structor your data or functions.
When if you work with a MYSQL database, then it would be a good idea, to make a PHP class to handle all communication with the database.

Creating a basic PHP class

<?php
  /* Create class names Utilities */
  class Utilities {
     /* create function to print a new line */
     function println(){
        print "<br/>\n";
     }
     /* create function to print data with a newline */
     function println($data){
        print $data ."<br />\n";
     }
  }
 
  /* 
     Using the class Utilities 
  */
 
  /* create instance of the class Utilities */ 
  $util = new Utilities();
 
  /* Using functions from Utilities */
 
  $util->println(); // prints <br />
  $util->println("Hello this is a test"); // prints Hello this is a test <br />
 
?>

Classes extends Class

When working with classes. Then you have the option of extending another class.

This is great when you are working, with data that has the sames values.
Ex. User data
A company can have more then only kind of employee. Here are but a few.

  • Normal employee
  • Marketing employee
  • Leders employee


Building classes to work with multi employees type

<php?
 
  /* creating common class Employee */
  class Employee{
     var $name;
     var $payment;
     var $department;
  }
 
  /* creating class for Marketing */
  class MarketingEmployer extends Employee{
     var $department="Marketing";
  }
 
  /* creating class for leders */
  class LedersEmployer extends Employee{
     var $department="Leders";
  }
 
  /* Using classes */
 
 
  $emp = new Employee();
  $emp->name = "John Doe";
  $emp->payment = "100.1";
 
  $emp1 = new MarketingEmployer();
  $emp1->name = "John Doe";
  $emp1->payment = "120.1";
 
  $emp2 = new LedersEmployer();
  $emp2->name = "Mr. John Doe";
  $emp2->payment = "200.1";
 
  /* debug output. view what emp's looks like */
  print "<pre>";
  var_dump($emp);
  var_dump($emp1);
  var_dump($emp2);
  print "</pre>";
 
?>

You can all so use classes in classes.
Using the last example.

Building classes to work with multi employees type with classes in classes

<php?
 
  /* creating common class Employee */
  class Employee{
     var $name;
     var $payment;
     var $department;
  }
 
  /* creating class for Marketing */
  class MarketingEmployer extends Employee{
     var $department="Marketing";
  }
 
  /* creating class for leders */
  class LedersEmployer extends Employee{
     var $department="Leders";
     var $employees;
  }
 
  /* Using classes */
 
 
  $emp = new Employee();
  $emp->name = "John Doe";
  $emp->payment = "100.1";
 
  $emp_x = new Employee();
  $emp_x->name = "Betty Sue";
  $emp_x->payment = "100.1";
 
 
  $emp1 = new MarketingEmployer();
  $emp1->name = "John Doe";
  $emp1->payment = "120.1";
 
  $emp2 = new LedersEmployer();
  $emp2->name = "Mr. John Doe";
  $emp2->payment = "200.1";
 
  $emp2->employees[] = $emp;
  $emp2->employees[] = $emp_x;
  $emp2->employees[] = $emp1;
 
 
 
  /* List people that work under Mr. John */
  for ($i=0;$i<count($emp2->employees);$i++){
    $employee = $emp2->employees[$i];
    print $employee->name . " work for Mr. John " . (($employee->department != "") ? " in department " . $employee->department : "") . "<br />";
  }
 
 
  /* debug output. view what emp2 looks like */
  print "<pre>";
  var_dump($emp2);
  print "</pre>";
 
?>

Building logic into classes

It's a good idea, to create a class. That can handel our logic.
In this example we are going to create a class to re-send a users password.

Creating Request Password Service

A Mysql table

   CREATE TABLE users(
      id int NOT NULL AUTO_INCREMENT,
      username varchar(100) NOT NULL,
      password varchar(100) NOT NULL,
      email text NOT NULL, 
      PRIMARY KEY(id)
   )

A class to re-send user's password

   <?php
      class ResendPassword{
 
         // Function to resend password
         function resendPassword ($email){
 
            //connect to MYSQL server
            mysql_connect("mysql.servername.com","john.doe","secretpassword");
 
            //select database
            mysql_select_db("johndoeDatabase");
 
            //build a safe SQL 
            $sql="select username,password from users where email='" . addslashes(trim($email)) . "'";
 
            //execute SQL
            $result=mysql_query($sql);
 
            //close MYSQL connection
            mysql_close();
 
            //check to see if we found the user.
            if ($row=mysql_fetch_array($result)){
               //read username
               $username=$row["username"];
               //read password
               $password=$row["password"];
               //create email text
               $email_text="Hi, $username\n\nYou requested your password from our server.\n" . 
                           "Your login information is:\n" .
                           "\tusername: $username\n\tpassword: $password\n\n" . 
                           "Best regards\nJohn Doe's Password service";
            } else {
               //create email text
               $email_text="Sorry but your email $email was not found in our userdatabase\n" . 
                           "Best regards\nJohn Doe's Password service";
            }
 
             //send a email
             mail($email,"Requested password",$email_text,"From: john.doe@password.service.com");
         }
      }
 
   ?>

Example use of ResendPassword

   <?php
 
      /*
       * include the php file. That have the ResendPassword class code in
       * In my example i saved the code in a file called ResendPassword.inc
       */
      include("ResendPassword.inc");
 
      //create a new instance of the class ResendPassword
      $resend = new ResendPassword();
 
      //now send the john.doe@hotmail.com his password. If he is in the users table.
      $resend->resendPassword("john.doe@hotmail.com");
 
   ?>

Creating UploadHandler

This time we are going to create a claas to upload files
The files will not be stored on server, but inside a MYSQL database.

A Mysql table

   CREATE TABLE DATA(
      id int NOT NULL AUTO_INCREMENT,
      filename varchar(200) NOT NULL,
      DATA blog,
      PRIMARY KEY(id)
   )

A class to upload files and store them in MYSQL

   <?php
      class UploadHandler{
 
         // a function to connect to MYSQL
         function connectDB (){
 
            //connect to MYSQL server
            mysql_connect("mysql.servername.com","john.doe","secretpassword");
 
            //select database
            mysql_select_db("johndoeDatabase");
         }
 
         // a function to close the connection to MYSQL
         function disconnectDB (){
 
            //close MYSQL connection
            mysql_close();
         }
 
         // a function to save file in MYSQL
         function storeFileInDB ($filename,$data){
 
            //build a safe SQL 
            $sql="insert into Data (filename,data) values ('" . addslashes(trim($filename)) . "','" . addslashes($data) . "')";
 
            //execute SQL
            mysql_query($sql);
         }
 
 
         // a function to upload the file
         function upload($name){
 
            //check to see if the files in uploaded
           if ($_FILES[$name]['tmp_name'] == ""){
              //No file found
              print "Sorry no file was uploaded!";
 
              //return from the function
              return false;
           }
 
           //connect to MYSQL 
           $this->connectDB();
 
           //Read the file
           $handle         = fopen($_FILES[$name]['tmp_name'], 'rb');
           $filecontents   = fread($handle, filesize($_FILES[$name]['tmp_name']));
           fclose($handle);
 
           //save the file in the database
           $this->storeFileInDB(basename($_FILES[$name]['tmp_name']),$filecontents);
 
           //disconnect to MYSQL 
           $this->disconnectDB();
 
         }
      }
 
   ?>

HTML FORM

   <h1>Select the file you like to upload</h1>
  <form>
     <!-- set max filesize for browser -->
     <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
 
     <!-- The field for the file. -->
     <input name="MyFileUpload" type="file" /> 
 
     <!-- Submit -->
     <input name="submit" type="submit" value="Upload file" /> 
  </form>

Example code of handling the Upload using the UploadHandler

   <?php
 
      /*
       * include the php file. That have the UploadHandler class code in
       * In my example i saved the code in a file called UploadHandler.inc
       */
      include("UploadHandler.inc");
 
      //create a new instance of the class UploadHandler
      $uploadhandler = new UploadHandler();
 
      //now try to upload the file selected from the HTML input field names "MyFileUpload"
      $uploadhandler->upload("MyFileUpload");
 
   ?>
 
understanding_php_classes.txt · Last modified: 2008/10/27 12:13 by michael
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki