Jul 7, 2011

PHP Object Oriented Programming



PHP stand for Hypertext Preprocessor is widely used, generally use as web development. PHP code usually embedded into HTML code and interpreted by a web server with PHP processor module.

PHP can be programmed as Procedural and Object Oriented(OOP).  Most likely, tutorial on the internet will teach by using the procedural programming.  Most probably, both method will produce the same result if coded in a correct way.

Why OOP? Some might be asking - Why should I start to code in OOP while procedural can do the things without any hiccup? Well I 'll answer it as "Suit yourself, it's your code not mine" if you asked me personally. But if you asked me reason on why I write mostly in OOP approach. The answer then is "I just want to keep myself DRY". DRY in programming world mean Don't Repeat Yourself. If you do read tutorials of tips on programming, you will probably heard this term DRY. Class and Object will make yourself DRY, so does procedural will make yourself WET?

To start doing OOP in PHP, the main things that we should have in mind is Class and Object. To have an object, we need class which will be the object templates. So before we start doing or messing with object, we need to create class. Below is an example of User class definition. The file below should be name as "User.php".

   1: <?php
   2:  
   3: require('Connection.php') ;
   4:  
   5: /**
   6:  *  User class will contain all function to handle User Model which will 
   7:  *  directly connected to MySQL by include connection.php on the 1st line before
   8:  *  class definition. This Php codes can be improve in many ways and please
   9:  *  contact me if any fix on codes. 
  10:  * ***********************************************
  11:  * @author GunbladeIV
  12:  * @tutorial Object Oriented Programming PHP
  13:  * @tutorial Negative Zero
  14:  * ***********************************************
  15:  * @param varchar $_userid (10)
  16:  * @param varchar $_username (50)
  17:  * @param varchar $_password (40)
  18:  * @param varchar $_fullname (150)
  19:  * @param varchar $_email (150)
  20:  * @param date $_birthdate 
  21:  * 
  22:  * @method 
  23:  */
  24: class User {
  25:  
  26:     // Private Var
  27:     var $_userid = null ;
  28:     var $_username = null ;
  29:     var $_password = null ;
  30:     var $_fullname = null ;
  31:     var $_email = null ;
  32:     var $_birthdate = null ;
  33:     // Var to hold database connection
  34:     var $_dbc ;
  35:  
  36:     function __construct() {
  37:         $this->_dbc = db_connect() ;
  38:     }
  39:  
  40:     function setUserid($uid) {
  41:         $this->_userid = $uid ;
  42:     }
  43:  
  44:     function getUserid() {
  45:         return $this->_userid ;
  46:     }
  47:  
  48:     function setUsername($username) {
  49:         $this->_username = $username ;
  50:     }
  51:  
  52:     function getUsername() {
  53:         return $this->_username ;
  54:     }
  55:  
  56:     function setPassword($pass) {
  57:         $this->_password = $pass ;
  58:     }
  59:  
  60:     function getPassword() {
  61:         return $this->_password ;
  62:     }
  63:  
  64:     function setFullname($name1, $name2=null) {
  65:         $this->name = $name1 . " " . $name2 ;
  66:     }
  67:     
  68:     function getFullname()
  69:     {
  70:         $this->_fullname;
  71:     }
  72:  
  73:     function setEmail($email) {
  74:         $this->_email = $email ;
  75:     }
  76:     
  77:     function getEmail()
  78:     {
  79:         return $this->_email;
  80:     }
  81:  
  82:     function setBirthdate($date) {
  83:         $this->_birthdate = $date ;
  84:     }
  85:     
  86:     function getBirthdate()
  87:     {
  88:         return $this->_birthdate;
  89:     }
  90:  
  91:     function setParamAll($var) {
  92:         if ( !is_object($var) ) {
  93:             $var = ( object ) $var ;
  94:         }
  95:         $this->_userid = $var->userid ;
  96:         $this->_username = $var->username ;
  97:         $this->_password = $this->_shaPassword($var->password) ;
  98:         $this->_fullname = $var->fullname ;
  99:         $this->_email = $var->email ;
 100:         $this->_birthdate = $var->birthdate ;
 101:     }
 102:  
 103:     function _shaPassword($pass) {
 104:         $var = sha1($pass) ;
 105:         return $var ;
 106:     }
 107:  
 108:     function setFromUserID($uid) {
 109:         if ( $this->_dbc ) {
 110:             $query = "SELECT * FROM user WHERE userid='$uid'" ;
 111:             $result = mysql_query($query) ;
 112:             if ( $result ) {
 113:                 $var = mysql_fetch_object($result) ;
 114:                 $this->setParamAll($var) ;
 115:             }
 116:             else {
 117:                 echo "ERROR RETRIEVING USER DATA FROM DATABASE" ;
 118:                 exit() ;
 119:             }
 120:         }
 121:     }
 122:  
 123:     function createUser($var) {
 124:         if ( !is_object($var) ) {
 125:             $var = ( object ) $var ;
 126:         }
 127:         $this->_setParamAll($var) ;
 128:         if ( $this->_dbc ) {
 129:             // CHECK IF USER ALREADY EXIST? 
 130:             // SHOULD THIS BE DONE ON VALIDATION?
 131:             $query = "INSERT INTO user VALUES " .
 132:                     "('$this->_userid','$this->_username','$this->_password'," .
 133:                     "'$this->_fullname','$this->_email','$this->_birthdate')" ;
 134:             $result = mysql_query($query) ;
 135:         }
 136:         if ( !$result ) {
 137:             return TRUE ;
 138:         }
 139:         else {
 140:             return FALSE ;
 141:         }
 142:     }
 143:  
 144: }
 145: ?>

From the User class definition, you can see that my variable is all in private while my methods/functions are mix with public and private. Generally, a private variable or function can only be access inside the class definition. Which mean, if I want to set $_username value from outside of the class User brackets, I need a method to pass the value. In above code, all the variable got their public set and get method which accessible on public.  Some function and method are kept private as we do not want it to be change or access from public. By practice to keep public as minimal as possible, we also did protect the object from unnecessary change from public or outside script.


How to use object when we do have the class? To declare object from our class, the syntax is simple, below is a file with PHP code that make use of above User class.



   1: <?php
   2: $_ClassUser = require('Class/User.php');
   3: if (!$_ClassUser)
   4: {
   5:     echo "User.php are missing. Please check your files directory for missing User.php";
   6: }
   7: /**
   8:  * Tutorial on how to use object based on User class.  The class is include
   9:  * above. Syntax to declare object based on User class as below:
  10:  * 
  11:  *     $object = new User;
  12:  * 
  13:  * How to use User class methods? the syntax as written below:
  14:  * 
  15:  *      $object->ClassName();  Only applicable if the method do not return value.
  16:  *      $var = $object->ClassName(); If the method return a value.
  17:  *                                   The value will be stored in $var.
  18:  *
  19:  * @author GunbladeIV
  20:  */
  21: //
  22: // include the User class
  23: //
  24: $user = new User ;
  25: //
  26: // Set username and userid using individually
  27: //
  28: $username = 'TestUser' ; // Give value to $username
  29: $uid = 'NZ-1' ; // Give value to $userid
  30:  
  31: $user->setUsername($username) ;
  32: $user->setUserid($uid) ;
  33: //
  34: // This two line above will set the Username and UserID. To check we ECHO
  35: //
  36: echo "User ID : " . $user->getUserid() . " And Username : " . $user->getUsername() ;
  37:  
  38: /**
  39:  * It is simple to use object if you need to do the same things on other file
  40:  * The object concept will keep yourself DRY. 
  41:  * Good luck!
  42:  */
  43:  
  44: ?>

The files above will show basic syntax on how you can code in OOP approach. Below is my Connection.php files that I used to link my PHP with MySQL just incase you having issue on missing include file.



   1: <?php
   2:  
   3: /*
   4:  * This will handle the connection to database which will then be require in 
   5:  * class file. The file will not contain any class. Only METHOD will be written
   6:  * here.
   7:  */
   8:  
   9: /**
  10:  * Description of the Connection.php File
  11:  * 
  12:  * This script will DEFINE _HOST, _USER, _PASS and _DBNAME.
  13:  * The script will contain:
  14:  * @method db_connect() use to connect on database.
  15:  * @return boolean $status
  16:  *
  17:  * @author GunBladeIV
  18:  */
  19:  
  20: DEFINE('_HOST','localhost');
  21: DEFINE('_USER','root');
  22: DEFINE('_PASS','');
  23: DEFINE('_DBNAME','negativezero');
  24:  
  25: function db_connect()
  26: {
  27:     $link = mysql_connect(_HOST,_USER,_PASS);
  28:     if ($link)
  29:     {
  30:         $status = mysql_select_db(_DBNAME);
  31:     }
  32:     else
  33:     {
  34:         $status = FALSE;
  35:         echo "MYSQL CONNECTION ERROR. PLEASE CHECK YOUR CONNECTION CONFIG";
  36:         exit();
  37:     }
  38:     
  39:     return $status;
  40: }
  41:  
  42: ?>

I hope this post will benefit you in some way.  Please consider to like this post on Facebook by clicking on FB like button below my post title. Leave a comments if you need explanation or help.


Thank you for your unbelievable support on Negative Zero - Permission to read and write blog for nearly 4 years. Don't forget to like Negative Zero on Facebook.
Blogirific.com Blog Directory





Post(s) you might like to read :

2 comments:

  1. Hey thanks for sharing this useful information.Especially for that DRY concept.I have never heard about it.

    Php Web Development

    ReplyDelete
  2. You are mostly welcome.Just wanna share the knowledge. This is the basic OOP on this post. I'll try to give example on more complex Object Oriented Programming to demonstrate on how you won't repeat yourself to prove the concept of DRY :-)

    ReplyDelete