database handling classes isys 475. introduction to classes a class is the blueprint for an object....
TRANSCRIPT
Introduction to Classes
• A class is the blueprint for an object. – It describes a particular type of object.– It specifies the properties (fields) and methods a
particular type of object can have.– One or more object can be created from the
class.– Each object created from a class is called an
instance of the class.
Adding a Class to a Project
• Right-click Source Files/New/PHP class– Assign a meaningful name.
• Steps:– Adding properties
• Property procedures: set / get• Or declare Public variables
– Adding methods
Class Code Example:Properties defined using Public variables
<?php
class emp {
public $eid;
public $ename;
public $salary;
public function empTax()
{
return $this->salary * .1;
}
}
?>
Using the emp Class:1. require it2. Creating an instance of the class using new
<?phprequire 'emp.php';$myEmp = new emp();$myEmp->eid='E1';$myEmp->ename='Peter';$myEmp->salary=5000.00;echo $myEmp->ename . ', your tax is: ' . $myEmp->empTax();?>
Creating Property with Property Procedures
• Implementing a property with a public variable the property value cannot be validated by the class.
• We can create read-only, write-only, or write-once properties with property procedure.
• Steps:– Declaring a private class variable to hold the property
value.
– Writing a property procedure to provide the interface to the property value.
class Employee { private $eid; private $ename; private $salary; public function getEID() { return $this->eid; } public function setEID($value) { $this->eid = $value; } public function getEname() { return $this->ename; } public function setEname($value) { $this->ename = $value; } public function getSalary() { return $this->salary; } public function setSalary($value) { $this->salary= $value; } public function empTax(){ return $this->salary*.1; } }
How the Property Procedure Works?
• When the program sets the property, the set property procedure is called and procedure code is executed. The value assigned to the property is passed in the value variable and is assigned to the hidden private variable.
• When the program reads the property, the get property procedure is called.
Using the Employee Class<?phprequire 'employee.php';$myEmp2 = new employee();$myEmp2->setEID("e2");$myEmp2->setEname("Paul");$myEmp2->setSalary(6500);
echo $myEmp2->getEname() . ', your tax is: ' . $myEmp2->empTax();
?>
Anatomy of a Class Module
Class Module
Public Variables & Property Procedures
Public Procedures & Functions
Exposed Part
Private Variables
Private Procedures & Functions
Hidden Part
•Private variables and procedures can be created for internal use.•Encapsulation
Encapsulation
• Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So methods like getter and setter access it and the other classes access it through property procedure.
Property Procedure Code Example:Enforcing a maximum value for salary
public function setSalary($value) { if ($value > 150000) $this->salary=150000; else $this->salary= $value; }
Expand the Employee Class with a DateHire property and Compute Years Employed
class Employee { private $eid; private $ename; private $salary; private $DateHire; private $yearsEmployed; public function getEID() { return $this->eid; } public function setEID($value) { $this->eid = $value; } public function getEname() { return $this->ename; } public function setEname($value) { $this->ename = $value; } public function getSalary() { return $this->salary; }
Continuepublic function setSalary($value) { if ($value > 150000) $this->salary=150000; else $this->salary= $value; } public function getDateHire(){ return $this->DateHire; } public function setDateHire($value){ $this->DateHire=$value; } public function getYearsEmployed(){ $hired = new DateTime($this->DateHire); $currentDate = new DateTime(); $interval= $hired->diff($currentDate); $this->yearsEmployed=$interval->format("a")/365.25; //$this->yearsEmployed=$currentDate->format("y")-$hired->format("y"); return $this->yearsEmployed; } public function empTax(){ return $this->salary*.1; }}
Implementing a Read-Only Property:Declare the property with only the get procedure
public function getYearsEmployed(){ $hired = new DateTime($this->DateHire); $currentDate = new DateTime(); $this->yearsEmployed=$currentDate->format("y")-$hired->format("y"); return $this->yearsEmployed; }
Note 1: PHP Date format: http://php.net/manual/en/function.date.php Note 2: PHP DateInterval format: http://www.php.net/manual/en/dateinterval.format.php
public function getYearsEmployed(){ $hired = new DateTime($this->DateHire); $currentDate = new DateTime(); $interval= $hired->diff($currentDate); $this->yearsEmployed=$interval->format("a")/365.25;
return $this->yearsEmployed; }
Example of Using the Employee Class
$myEmp2 = new employee();$myEmp2->setEID("e2");$myEmp2->setEname("Paul");$myEmp2->setSalary(65000);$myEmp2->setDateHire("12/25/2005");echo $myEmp2->getYearsEmployed();echo $myEmp2->getEname() . ', your tax is: ' . $myEmp2->empTax();
Inheritance
• The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.
Employee Super Class with Three SubClasses
All employee subtypes will have emp nbr, name, address, and date-hired
Each employee subtype will also have its own attributes
Inheritance Exampleclass secretary extends employee{
private $WPM;
public function getWPM() {
return $this->WPM;
}
public function setWPM($value) {
$this->WPM = $value;
}
}
Method Override
public function empTax(){ return $this->getSalary()*.15; }
If we were to create a method in the child class having the same name, same number of parameters and the same access specifier as in it’s parent then we can say that we are doing method overriding. Example, add an empTax function with 15% tax rate to the secretrary class:
Single-Record-Handling Classes
– Retrieves a single record from the database and makes it available to your application in the form of an object.
– The fields in the record are exposed as the object’s properties.
– Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.
PHP List
• Assign variables as if they were an array• Example:
$info = array('coffee', 'brown', 'caffeine');list($drink, $color, $power) = $info;echo "$drink is $color and $power makes it special.";
Single-Record-Handling Class Exampleclass Customer {
public $cid;
public $cname;
public $city;
public $rating;
public function getCustomerData($searchID){
$dsn = 'mysql:host=localhost;dbname=salesdb';
$username = 'root';
$password = '';
$db = new PDO($dsn, $username, $password);
$query = "SELECT * FROM customers WHERE CID='" . $searchID . "'";
$customers = $db->query($query);
//$customer=$customers->fetch(); return list($this->cid, $this->cname, $this->city, $this->rating) = $customers->fetch(PDO::FETCH_NUM);
}
Note: the fetch method returns true/false, so the getCustomerData is a boolean function.
public function addNewCustomer(){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $queryINS = "insert into customers value('" . $this->cid . "','" . $this->cname . "','" . $this->city . "','" . $this->rating . "')"; return $db->exec($queryINS); }
Adding a New Customer:
Note: the exec method returns the number of records affected by the SQL statement and in this case returns 1 if insertion is successful.
Using the Customer Class to Add a New Customer
<form name="newCustomerForm" action="newCustomer.php" method="POST"> CID: <input type="text" name="CID" value="" /><br><br> Cname: <input type="text" name="Cname" value="" /><br><br> City: <input type="text" name="City" value="" /><br><br> Rating: <input type="text" name="Rating" value="" /><br><br> <input type="submit" value="Add New Customer" name="btnSubmit" />
Using the addNewCustomer PHP:require 'Customer.php';
<?phptry{require 'Customer.php';$myCust=new Customer();$myCust->cid=$_POST["CID"]; $myCust->cname=$_POST["Cname"]; $myCust->city=$_POST["City"]; $myCust->rating=$_POST["Rating"]; if ($myCust->addNewCustomer()==1) echo "Adding succesful";else echo "Adding not succesful";} catch (Exception $e) { $error_message = $e->getMessage(); echo "<p>Error message: $error_message </p>"; }?>
Using the Customer Class to Retrieve Data
<?phptry{require 'Customer.php';$myCust=new Customer();$cid=$_GET["CID"];if ($myCust->getCustomerData($cid)) echo $myCust->cname . $myCust->city . $myCust->rating;else echo "Record not exist";}catch (Exception $e) { $error_message = $e->getMessage(); echo "<p>Error message: $error_message </p>"; }?>
Other Methods
• Updating a record
• Deleting a record
• Note: CRUD– Create or add new entries– Read, retrieve, search, or view existing entries– Update or edit existing entries– Delete/deactivate existing entries
Modeling 1:M Relation with Classes
• Employee– EID– Ename– Dependents
• Department– DID– Dname– Employees
• Customer– CID– Cname– Orders
Arrays
• An array in PHP is actually an ordered map. A map is a type that associates values to keys.
• An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
Declare and Access an Array• Declare:
array(key1 => value, key2 => value2, key3 => value3, ... )
• Example:
$courseArray=array();$courseArray["ISYS263"]="Introduction Information System";$courseArray["ISYS363"]="Information Systems for Management";$courseArray["ISYS350"]="Business Application Development";
Accessing an member by its key:echo $courseArray["ISYS363"];
Declare an array without key
• The key is optional. If it is not specified, PHP will use 0-based integer key.
$courseArray=array();$courseArray[0]="Introduction Information System";$courseArray[1]="Information Systems for Management";$courseArray[2]="Business Application Development";echo $courseArray[1];
array_filter• $data = array(42, “foo”, 96, “”, 100.96, “php”);• // Filter each value of $data through the function
is_numeric• $numeric_data = array_filter($data,
“is_numeric”);• // Re-key the array so the keys are sequential and
numeric (starting at 0)• $numeric_data = array_values($numeric_data);
array_push: Push one or more elements onto the end of array
Array( [0] => orange [1] => banana [2] => apple [3] => raspberry)
<?php$stack = array("orange", "banana");array_push($stack, "apple", "raspberry");print_r($stack);?>
array_pop — Pop the element off the end of array
<?php$stack = array("orange", "banana", "apple", "raspberry");$fruit = array_pop($stack);print_r($stack);?>
Array( [0] => orange [1] => banana [2] => apple)
Remove an item from an array with unset command
• Use Index to Remove Array:$fruits = array("orange", "banana", "apple", "raspberry");
unset($fruits[2]); print_r($fruits);
Result: Array ( [0] => orange [1] => banana [3] => raspberry )
• Use specified key to delete array element:$fruits = array('fruit1' => "orange", 'fruit2' => "banana", 'fruit3' => "apple", 'fruit4' => "raspberry");
unset($fruits['fruit3']);
print_r($fruits);
Result: Array ( [fruit1] => orange [fruit2] => banana [fruit4] => raspberry )
Use array_values to reindex the array to fix the hole created by unset with index
$fruits = array("orange", "banana", "apple", "raspberry");unset($fruits[2]);$fruits=array_values($fruits);print_r($fruits);
Result: Array ( [0] => orange [1] => banana [2] => raspberry )
Implementing a 1:M Relationship With Array
CIDCnameCityRatingOrders --- an array of instances of order classMethods:
GetOrdersGetOrders
OIDOdateSalesPerson
Class Customer
Class Order
Customer Class Properties
public $cid;
public $cname;
public $city;
public $rating;
public $orders = array();
GetOrders Methodpublic function getOrders($searchID){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM orders WHERE CID='" . $searchID . "'"; $customers = $db->query($query); foreach ($customers as $row) { $order=new Order(); $order->oid=$row["oid"]; $order->cid=$row["cid"]; $order->sid=$row["sid"]; $order->odate=$row["odate"]; array_push($this->orders, $order); } }
<?phptry{require 'Customer.php';require 'Order.php';$myCust=new Customer();$cid=$_GET["CID"];if ($myCust->getCustomerData($cid)){ echo "Customer name: " . $myCust->cname . "<br><br>"; echo "City: " . $myCust->city . "<br><br>"; echo "Rating: " . $myCust->rating . "<br><br>"; $myCust->getOrders($cid); echo "<table border=1><tr>" . "<th>OID</th>" . "<th>CID</th>" . "<th>SID</th>" . "<th>Odate</th></tr>"; $length=count($myCust->orders); for ($i=0;$i<$length;++$i){ $oid=$myCust->orders[$i]->oid; $cid=$myCust->orders[$i]->cid; $sid=$myCust->orders[$i]->sid; $odate=$myCust->orders[$i]->odate; echo "<tr><td>$oid</td>" . "<td>$cid</td>" . "<td>$sid</td>" . "<td>$odate</td></tr>"; } echo "</table>";}else echo "Record not exist";}catch (Exception $e) { $error_message = $e->getMessage(); echo "<p>Error message: $error_message </p>"; }?>
Customer Class
public $cid;public $cname;public $city;public $rating;public $orders = array();Methods:
getCustomerDatagetOrders
Order Class:
class Order { public $oid; public $cid; public $sid; public $odate; public $details=array();
getDetails methodpublic function getDetails($searchID){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM orderdetail WHERE OID='" . $searchID . "'"; $details = $db->query($query); foreach ($details as $row) { $detail=new OrderDetail(); $detail->oid=$row["oid"]; $detail->pid=$row["pid"]; $detail->pname=$row["pname"]; $detail->qty=$row["qty"]; $detail->price=$row["price"]; $detail->amount=$row["amount"]; array_push($this->details, $detail); } }
OrderDetail class:
class OrderDetail { public $oid; public $pid; public $pname; public $qty; public $price; public $amount;}
MySQL View
Create view orderdetail asSelect oid, pid,pname,qty,price,qty*price as amountFrom products natural join odetails;
Use the view as a table:$query = "SELECT * FROM orderdetail WHERE OID='" . $searchID . "'";
PHP using the classes<?php require 'Customer.php'; require 'Order.php'; require 'OrderDetail.php'; $mycust=new Customer(); $mycust->getCustomerData('C1'); $mycust->getOrders('C1'); echo "CID: $mycust->cid Name: $mycust->cname City: $mycust->city Rating: $mycust->rating <br>"; echo "<table border=1><tr>" . "<th>OID</th>" . "<th>CID</th>" . "<th>Odate</th>" . "<th>SID</th></tr>"; foreach ($mycust->orders as $order) { $oid=$order->oid; $cid=$order->cid; $odate=$order->odate; $sid=$order->sid; $order->getDetails($oid); echo "<tr><td>$oid</td>" . "<td>$cid</td>" . "<td>$odate</td>" . "<td>$sid</td></tr>"; echo "<tr><td>Details:OID</td>" . "<td>PID</td>" . "<td>PNAME</td>" . "<td>QTY</td>" . "<td>PRICE</td>" . "<td>AMOUNT</td>" . "</tr>"; foreach ($order->details as $detail) { $oid=$detail->oid; $pid=$detail->pid; $pname=$detail->pname; $qty=$detail->qty; $price=$detail->price; $amount=$detail->amount; echo "<tr><td>$oid</td>" . "<td>$pid</td>" . "<td>$pname</td>" . "<td>$qty</td>" . "<td>$price</td>" . "<td>$amount</td>" . "</tr>"; }}echo "</table>"; ?>
Entity Class Generator:NetBeans PHP Database Class Plugin
• Db2php:– http://code.google.com/p/db2php/– Or:– http://plugins.netbeans.org/plugin/41522/db2php– File name: db2phpnb-1.107.nbm– Save as:
Example of using the class• http://code.google.com/p/db2php/wiki/HOWTO• interface Db2PhpEntity:– http://code.google.com/p/db2php/source/browse/db
2phplib/src/main/resources/org/afraid/poison/db2php/generator/utility/Db2PhpEntity.class.php?r=9c9474937cae0d2dc73ee55aafde0897c58bf2bf
• abstract class Db2PhpEntityBase implements Db2PhpEntity:– http://code.google.com/p/db2php/source/browse/
db2phplib/src/main/resources/org/afraid/poison/db2php/generator/utility/Db2PhpEntityBase.class.php?r=3135161710d01bfabf9a5add0d1ddc6098766137
Using the Class
<?php include 'db2phpclass.php'; require 'CustomersModel.class.php'; $db= new PDO('mysql:host=localhost;dbname=salesdb', 'root', ''); $customer = new CustomersModel(); $sql="select * from customers where cid='C1'"; $results=$customer->findBySql($db, $sql); echo var_dump($results); echo $results[0]->getCname(); ?>
PEAR - PHP Extension and Application Repository
• Home Page:– http://pear.php.net/index.php
• PEAR is a framework and distribution system for reusable PHP components.