Database Handling Classes - PowerPoint PPT Presentation

Loading...

PPT – Database Handling Classes PowerPoint presentation | free to download - id: 56afcc-NjYyZ



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

Database Handling Classes

Description:

Database Handling Classes ISYS 475 * * * * array ... Database Handling Classes Data Source Database Classes Web Pages Single-Record-Handling Classes Retrieves a ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 59
Provided by: cob
Learn more at: http://online.sfsu.edu
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: Database Handling Classes


1
Database Handling Classes
  • ISYS 475

2
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.

3
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

4
Class Code ExampleProperties defined using
Public variables
lt?php class emp public eid public
ename public salary public function
empTax() return
this-gtsalary .1 ?gt
5
Using the emp Class1. require it2. Creating an
instance of the class using new
lt?php require 'emp.php' myEmp new
emp() myEmp-gteid'E1' myEmp-gtename'Peter' m
yEmp-gtsalary5000.00 echo myEmp-gtename . ',
your tax is ' . myEmp-gtempTax() ?gt
6
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.

7
class Employee private eid
private ename private salary public
function getEID() return this-gteid
public function setEID(value)
this-gteid value public function
getEname() return this-gtename
public function setEname(value)
this-gtename value public function
getSalary() return this-gtsalary
public function setSalary(value)
this-gtsalary value public
function empTax() return
this-gtsalary.1
8
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.

9
Using the Employee Class
lt?php require 'employee.php' myEmp2 new
employee() myEmp2-gtsetEID("e2") myEmp2-gtsetEna
me("Paul") myEmp2-gtsetSalary(6500) echo
myEmp2-gtgetEname() . ', your tax is ' .
myEmp2-gtempTax() ?gt
10
Anatomy of a Class Module
Class Module
Exposed Part
Hidden Part
Public Variables Property Procedures
Private Variables
Public Procedures Functions
Private Procedures Functions
  • Private variables and procedures can be created
    for internal use.
  • Encapsulation

11
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.

12
Property Procedure Code ExampleEnforcing a
maximum value for salary
public function setSalary(value) if
(value gt 150000) this-gtsalary150000
else this-gtsalary
value
13
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-gteid
public function setEID(value)
this-gteid value public function
getEname() return this-gtename
public function setEname(value)
this-gtename value public function
getSalary() return this-gtsalary

14
Continue
public function setSalary(value) if
(value gt 150000) this-gtsalary150000
else this-gtsalary
value public function getDateHire()
return this-gtDateHire public
function setDateHire(value)
this-gtDateHirevalue public function
getYearsEmployed() hired new
DateTime(this-gtDateHire) currentDate
new DateTime() interval
hired-gtdiff(currentDate)
this-gtyearsEmployedinterval-gtformat("a")/365.25
//this-gtyearsEmployedcurrentDate-gtfor
mat("y")-hired-gtformat("y")
return this-gtyearsEmployed public
function empTax() return
this-gtsalary.1
15
Implementing a Read-Only PropertyDeclare the
property with only the get procedure
public function getYearsEmployed()
hired new DateTime(this-gtDateHire)
currentDate new DateTime()
this-gtyearsEmployedcurrentDate-gtformat("y")-hi
red-gtformat("y") return
this-gtyearsEmployed
public function getYearsEmployed()
hired new DateTime(this-gtDateHire)
currentDate new DateTime()
interval hired-gtdiff(currentDate)
this-gtyearsEmployedinterval-gtformat("a")/365.25
return this-gtyearsEmployed
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
16
Example of Using the Employee Class
myEmp2 new employee() myEmp2-gtsetEID("e2")
myEmp2-gtsetEname("Paul") myEmp2-gtsetSalary(65000
) myEmp2-gtsetDateHire("12/25/2005") echo
myEmp2-gtgetYearsEmployed() echo
myEmp2-gtgetEname() . ', your tax is ' .
myEmp2-gtempTax()
17
Inheritance
  • The process in which a new class can be based on
    an existing class, and will inherit that classs
    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.

18
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
19
Inheritance Example
class secretary extends employee private
WPM public function getWPM() return
this-gtWPM public function
setWPM(value) this-gtWPM value

20
Method Override
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 its parent
then we can say that we are doing method
overriding. Example, add an empTax function with
15 tax rate to the secretrary class
public function empTax() return
this-gtgetSalary().15
21
Database Handling Classes
Database Classes
Data Source
Web Pages
22
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
    objects properties.
  • Any actions performed by the data (updates,
    calculations, etc.) are exposed as the objects
    methods.

23
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."
24
Single-Record-Handling Class Example
class Customer public cid public
cname public city public rating
public function getCustomerData(searchID)
dsn 'mysqlhostlocalhostdbnamesalesdb'
username 'root' password
'' db new PDO(dsn, username,
password) query "SELECT FROM
customers WHERE CID'" . searchID . "'"
customers db-gtquery(query)
//customercustomers-gtfetch() return
list(this-gtcid, this-gtcname, this-gtcity,
this-gtrating) customers-gtfetch(PDOFETCH_NUM)

Note the fetch method returns true/false, so the
getCustomerData is a boolean function.
25
Adding a New Customer
public function addNewCustomer() dsn
'mysqlhostlocalhostdbnamesalesdb'
username 'root' password ''
db new PDO(dsn, username, password)
queryINS "insert into customers value('"
. this-gtcid . "','" . this-gtcname . "','" .
this-gtcity . "','" .
this-gtrating . "')" return
db-gtexec(queryINS)
Note the exec method returns the number of
records affected by the SQL statement and in this
case returns 1 if insertion is successful.
26
Using the Customer Class to Add a New Customer
ltform name"newCustomerForm" action"newCustomer.p
hp" method"POST"gt CID ltinput
type"text" name"CID" value"" /gtltbrgtltbrgt
Cname ltinput type"text" name"Cname"
value"" /gtltbrgtltbrgt City ltinput
type"text" name"City" value"" /gtltbrgtltbrgt
Rating ltinput type"text" name"Rating"
value"" /gtltbrgtltbrgt ltinput
type"submit" value"Add New Customer"
name"btnSubmit" /gt
27
Using the addNewCustomer PHPrequire
'Customer.php'
lt?php try require 'Customer.php' myCustnew
Customer() myCust-gtcid_POST"CID"
myCust-gtcname_POST"Cname"
myCust-gtcity_POST"City" myCust-gtrating_
POST"Rating" if (myCust-gtaddNewCustomer()1)
echo "Adding succesful" else echo
"Adding not succesful" catch (Exception e)
error_message e-gtgetMessage() echo
"ltpgtError message error_message lt/pgt" ?gt
28
Using the Customer Class to Retrieve Data
lt?php try require 'Customer.php' myCustnew
Customer() cid_GET"CID" if
(myCust-gtgetCustomerData(cid)) echo
myCust-gtcname . myCust-gtcity .
myCust-gtrating else echo "Record not
exist" catch (Exception e)
error_message e-gtgetMessage() echo
"ltpgtError message error_message lt/pgt" ?gt
29
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

30
Modeling 1M Relation with Classes
  • Employee
  • EID
  • Ename
  • Dependents
  • Department
  • DID
  • Dname
  • Employees
  • Customer
  • CID
  • Cname
  • Orders

31
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 gt value pairs as arguments.

32
Declare and Access an Array
  • Declare
  • array(key1 gt value, key2 gt value2, key3 gt
    value3, ... )
  • Example

courseArrayarray() courseArray"ISYS263""Int
roduction Information System" courseArray"ISYS3
63""Information Systems for Management" course
Array"ISYS350""Business Application
Development"
Accessing an member by its key echo
courseArray"ISYS363"
33
Declare an array without key
  • The key is optional. If it is not specified, PHP
    will use 0-based integer key.

courseArrayarray() courseArray0"Introductio
n Information System" courseArray1"Informatio
n Systems for Management" courseArray2"Busine
ss Application Development" echo courseArray1
34
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)

35
array_push Push one or more elements onto the
end of array
lt?php stack array("orange", "banana") array_pu
sh(stack, "apple", "raspberry") print_r(stack)
?gt
Array ( 0 gt orange 1 gt banana
2 gt apple 3 gt raspberry )
36
array_pop Pop the element off the end of array
lt?php stack array("orange", "banana", "apple",
"raspberry") fruit array_pop(stack) print_r(
stack) ?gt
Array ( 0 gt orange 1 gt banana
2 gt apple )
37
Remove an item from an array with unset command
  • Use Index to Remove Array
  • fruits array("orange", "banana", "apple",
    "raspberry")
  • unset(fruits2) print_r(fruits)
  • Result Array ( 0 gt orange 1 gt banana 3
    gt raspberry )
  • Use specified key to delete array element
  • fruits array('fruit1' gt "orange", 'fruit2' gt
    "banana", 'fruit3' gt "apple", 'fruit4' gt
    "raspberry")
  • unset(fruits'fruit3')
  • print_r(fruits)
  • Result Array ( fruit1 gt orange fruit2 gt
    banana fruit4 gt raspberry )

38
Use array_values to reindex the array to fix the
hole created by unset with index
fruits array("orange", "banana", "apple",
"raspberry") unset(fruits2) fruitsarray_val
ues(fruits) print_r(fruits)
Result Array ( 0 gt orange 1 gt banana 2
gt raspberry )
39
Implementing a 1M Relationship With Array
Class Customer
CID Cname City Rating Orders --- an array of
instances of order class Methods
GetOrders GetOrders
Class Order
OID Odate SalesPerson
40
Customer Class Properties
public cid public cname public city public
rating public orders array()
41
Order Class
class Order public oid public cid
public sid public odate
42
GetOrders Method
public function getOrders(searchID)
dsn 'mysqlhostlocalhostdbnamesalesdb'
username 'root' password ''
db new PDO(dsn, username, password)
query "SELECT FROM orders WHERE
CID'" . searchID . "'" customers
db-gtquery(query) foreach (customers
as row) ordernew Order()
order-gtoidrow"oid"
order-gtcidrow"cid"
order-gtsidrow"sid"
order-gtodaterow"odate"
array_push(this-gtorders, order)
43
Example
44
lt?php try require 'Customer.php' require
'Order.php' myCustnew Customer() cid_GET"C
ID" if (myCust-gtgetCustomerData(cid))
echo "Customer name " . myCust-gtcname .
"ltbrgtltbrgt" echo "City " . myCust-gtcity .
"ltbrgtltbrgt" echo "Rating " . myCust-gtrating
. "ltbrgtltbrgt" myCust-gtgetOrders(cid)
echo "lttable border1gtlttrgt" . "ltthgtOIDlt/thgt" .
"ltthgtCIDlt/thgt" . "ltthgtSIDlt/thgt" .
"ltthgtOdatelt/thgtlt/trgt" lengthcount(myCust-
gtorders) for (i0iltlengthi)
oidmyCust-gtordersi-gtoid
cidmyCust-gtordersi-gtcid
sidmyCust-gtordersi-gtsid
odatemyCust-gtordersi-gtodate echo
"lttrgtlttdgtoidlt/tdgt" . "lttdgtcidlt/tdgt" .
"lttdgtsidlt/tdgt" . "lttdgtodatelt/tdgtlt/trgt"
echo "lt/tablegt" else echo "Record not
exist" catch (Exception e)
error_message e-gtgetMessage() echo
"ltpgtError message error_message lt/pgt" ?gt
45
A page with data from 4 tablesCustomers,
Orders, Details, Products
46
Customer Class
public cid public cname public city public
rating public orders array() Methods getCu
stomerData getOrders
47
Order Class
class Order public oid public cid
public sid public odate public
detailsarray()
48
getDetails method
public function getDetails(searchID)
dsn 'mysqlhostlocalhostdbnamesalesdb'
username 'root' password
'' db new PDO(dsn, username,
password) query "SELECT FROM
orderdetail WHERE OID'" . searchID . "'"
details db-gtquery(query) foreach
(details as row) detailnew
OrderDetail() detail-gtoidrow"oid"
detail-gtpidrow"pid"
detail-gtpnamerow"pname"
detail-gtqtyrow"qty"
detail-gtpricerow"price"
detail-gtamountrow"amount"
array_push(this-gtdetails, detail)

49
OrderDetail class
class OrderDetail public oid public
pid public pname public qty public
price public amount
50
MySQL View
Create view orderdetail as Select oid,
pid,pname,qty,price,qtyprice as amount From
products natural join odetails
Use the view as a table query "SELECT FROM
orderdetail WHERE OID'" . searchID . "'"
51
PHP using the classes
lt?php require 'Customer.php'
require 'Order.php' require
'OrderDetail.php' mycustnew
Customer() mycust-gtgetCustomerData('C1')
mycust-gtgetOrders('C1') echo
"CID mycust-gtcid Name mycust-gtcname City
mycust-gtcity Rating mycust-gtrating ltbrgt"
echo "lttable border1gtlttrgt" . "ltthgtOIDlt/thgt"
. "ltthgtCIDlt/thgt" . "ltthgtOdatelt/thgt" .
"ltthgtSIDlt/thgtlt/trgt" foreach (mycust-gtorders
as order) oidorder-gtoid
cidorder-gtcid odateorder-gtodate
sidorder-gtsid
order-gtgetDetails(oid) echo
"lttrgtlttdgtoidlt/tdgt" . "lttdgtcidlt/tdgt" .
"lttdgtodatelt/tdgt" . "lttdgtsidlt/tdgtlt/trgt"
echo "lttrgtlttdgtDetailsOIDlt/tdgt" . "lttdgtPIDlt/tdgt"
. "lttdgtPNAMElt/tdgt" . "lttdgtQTYlt/tdgt" .
"lttdgtPRICElt/tdgt" . "lttdgtAMOUNTlt/tdgt" . "lt/trgt"
foreach (order-gtdetails as detail)
oiddetail-gtoid piddetail-gtpid
pnamedetail-gtpname qtydetail-gtqty
pricedetail-gtprice
amountdetail-gtamount echo
"lttrgtlttdgtoidlt/tdgt" . "lttdgtpidlt/tdgt" .
"lttdgtpnamelt/tdgt" . "lttdgtqtylt/tdgt" .
"lttdgtpricelt/tdgt" . "lttdgtamountlt/tdgt" .
"lt/trgt" echo "lt/tablegt" ?gt
52
Entity Class GeneratorNetBeans 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

53
Add the plugIn
  • NetBeans
  • Tools/PlugIns/Downloaded/Add PlugIns

54
Using the db2php plugin
  • Sources File/New/Other/PHP Entity Class from
    Database

55
Example of using the class
  • http//code.google.com/p/db2php/wiki/HOWTO
  • interface Db2PhpEntity
  • http//code.google.com/p/db2php/source/browse/db2p
    hplib/src/main/resources/org/afraid/poison/db2php/
    generator/utility/Db2PhpEntity.class.php?r9c94749
    37cae0d2dc73ee55aafde0897c58bf2bf
  • abstract class Db2PhpEntityBase implements
    Db2PhpEntity
  • http//code.google.com/p/db2php/source/browse/db2p
    hplib/src/main/resources/org/afraid/poison/db2php/
    generator/utility/Db2PhpEntityBase.class.php?r313
    5161710d01bfabf9a5add0d1ddc6098766137

56
Using the Class
lt?php include 'db2phpclass.php'
require 'CustomersModel.class.php' db
new PDO('mysqlhostlocalhostdbnamesalesdb',
'root', '') customer new
CustomersModel() sql"select from
customers where cid'C1'"
resultscustomer-gtfindBySql(db, sql)
echo var_dump(results) echo
results0-gtgetCname() ?gt
57
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.

58
DB_Table
  • http//pear.php.net/manual/en/package.database.db-
    table.php
About PowerShow.com