Chapter 2 Part9
Chapter 2 Part9
Content
2.1. How to work with form data
2.2. How to code control statements
2.3. How to work with string and numbers
2.4. How to work with dates
2.5. How to work with arrays
2.6. How to work with cookie
2.7. How to work with session
2.8. How to work with functions
2.9. How to work with objects
2.10. How to work with regular expression, handle exception
C1, Slide 2
2.9. How to work with objects
Objectives
Applied
1. Create and use your own classes, objects, properties, and
methods.
2. Create and use your own class constants, static properties, and
static methods.
3. Use your own classes and objects to implement the MVC pattern.
C14, Slide 3
Objectives (continued)
Knowledge
1. Describe the creation of a class including its properties and
methods.
2. Describe the use of the $this variable in a class.
3. Describe the creation of an object from a class and the use of the
object’s properties and methods.
4. Describe the use of class constants and static properties and
methods.
5. Describe the differences between applications that use procedural
techniques for implementing the MVC pattern and those that use
object-oriented techniques.
6. Describe how inheritance works.
C14, Slide 4
The Category class
class Category {
private $id;
private $name;
C14, Slide 5
Key terms
object-oriented programming
class
object
property
method
C14, Slide 6
The Product class
class Product {
private $category, $id, $code, $name, $price;
C14, Slide 7
The Product class (continued)
public function getCategory() {
return $this->category;
}
C14, Slide 8
The Product class (continued)
public function getCode() {
return $this->code;
}
C14, Slide 9
The Product class (continued)
public function getPrice() {
return $this->price;
}
C14, Slide 10
The Product class (continued)
public function getDiscountPercent() {
$discount_percent = 30;
return $discount_percent;
}
C14, Slide 11
The Product class (continued)
public function getDiscountPrice() {
$discount_price =
$this->price - $this->getDiscountAmount();
$discount_price_f =
number_format($discount_price, 2);
return $discount_price_f;
}
C14, Slide 12
The Product class (continued)
public function getImageFilename() {
$image_filename = $this->code . '.png';
return $image_filename;
}
C14, Slide 13
The syntax for coding a property
[ public | protected | private ] $propertyName
[ = initialValue ];
A private property
private $firstName;
A protected property
protected $counter;
C14, Slide 14
Key terms
public property
private property
protected property
scalar value
C14, Slide 15
The syntax for coding a constructor method
public function __construct([parameterList]) {
// Statements to execute
}
C14, Slide 16
How to code a destructor method
The syntax
public function __destruct() {
// Statements to execute
}
A destructor for a database class
public function __destruct() {
$this->dbConnection->close();
}
C14, Slide 17
Key terms
constructor method
constructor
destructor method
destructor
object access operator
C14, Slide 18
The syntax for coding a method
[public | private | protected]
function functionName ([parameterList]) {
// Statements to execute
}
A public method
public function getSummary() {
$maxLength = 25;
$summary = $this->description;
if (strlen($summary) > $maxLength) {
$summary =
substr($summary, 0, $maxLength - 3) . '...';
}
return $summary;
}
C14, Slide 19
A private method
private function internationalizePrice($country = 'US') {
switch ($country) {
case 'US':
return '$' . number_format($this->price, 2);
case 'FR':
return number_format(
$this->price, 2, ',' , '.') . ' EUR';
default:
return number_format($this->price, 2);
}
}
C14, Slide 20
A method that accesses a property
of the current object
public function showDescription() {
echo $this->description;
}
C14, Slide 21
The syntax for creating an object
$objectName = new ClassName(argumentList);
C14, Slide 22
The syntax for setting a public property value
$objectName->propertyName = value;
Setting a property
$trumpet->comment = 'Discontinued';
Getting a property
echo $trumpet->comment;
C14, Slide 23
The syntax for calling an object’s methods
$objectName->methodName(argumentList);
Object chaining
echo $trumpet->getCategory()->getName();
C14, Slide 24
Key terms
instance of a class
instantiation
object chaining
C14, Slide 25
A class with three class constants
class Person {
const GREEN_EYES = 1;
const BLUE_EYES = 2;
const BROWN_EYES = 3;
private $eye_color;
C14, Slide 26
Using a constant outside the class
$person = new Person();
$person->setEyeColor(Person::GREEN_EYES);
C14, Slide 27
A class with a static property and method
class Category {
private $id, $name;
private static $objectCount = 0;
// declare a static property
C14, Slide 28
Using a public static method
$guitars = new Category(1, 'Guitars');
$basses = new Category(2, 'Basses');
echo '<p>Object count: ' .
Category::getObjectCount() . '</p>'; // 2
C14, Slide 29
Key terms
class constant
scope resolution operator
static property
static method
class property
class method
C14, Slide 30
The Product List page
C14, Slide 31
The Add Product page
C14, Slide 32
The database.php file
<?php
class Database {
private static $dsn =
'mysql:host=localhost;dbname=my_guitar_shop1';
private static $username = 'mgs_user';
private static $password = 'pa55word';
private static $db;
C14, Slide 33
The database.php file (continued)
public static function getDB() {
if (!isset(self::$db)) {
try {
self::$db = new PDO(self::$dsn,
self::$username,
self::$password);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('../errors/database_error.php');
exit();
}
}
return self::$db;
}
}
?>
C14, Slide 34
The product_db.php file
<?php
class ProductDB {
public static function getProductsByCategory($category_id) {
$db = Database::getDB();
$category = CategoryDB::getCategory($category_id);
$query = 'SELECT * FROM products
WHERE products.categoryID = :category_id
ORDER BY productID';
$statement = $db->prepare($query);
$statement->bindValue(":category_id", $category_id);
$statement->execute();
$rows = $statement->fetchAll();
$statement->closeCursor();
foreach ($rows as $row) {
$product = new Product($category,
$row['productCode'],
$row['productName'],
$row['listPrice']);
$product->setId($row['productID']);
$products[] = $product;
}
return $products;
}
C14, Slide 35
The product_db.php file (continued)
public static function getProduct($product_id) {
$db = Database::getDB();
$query = 'SELECT * FROM products
WHERE productID = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(":product_id", $product_id);
$statement->execute();
$row = $statement->fetch();
$statement->closeCursor();
$category = CategoryDB::getCategory($row['categoryID']);
$product = new Product($category,
$row['productCode'],
$row['productName'],
$row['listPrice']);
$product->setID($row['productID']);
return $product;
}
C14, Slide 36
The product_db.php file (continued)
public static function deleteProduct($product_id) {
$db = Database::getDB();
$query = 'DELETE FROM products
WHERE productID = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(':product_id', $product_id);
$statement->execute();
$statement->closeCursor();
}
C14, Slide 37
The product_db.php file (continued)
public static function addProduct($product) {
$db = Database::getDB();
$category_id = $product->getCategory()->getID();
$code = $product->getCode();
$name = $product->getName();
$price = $product->getPrice();
C14, Slide 38
The index.php file
<?php
require('../model/database.php');
require('../model/category.php');
require('../model/category_db.php');
require('../model/product.php');
require('../model/product_db.php');
C14, Slide 39
The index.php file (continued)
if ($action == 'list_products') {
$category_id = filter_input(INPUT_GET, 'category_id',
FILTER_VALIDATE_INT);
if ($category_id == NULL || $category_id == FALSE) {
$category_id = 1;
}
$current_category = CategoryDB::getCategory($category_id);
$categories = CategoryDB::getCategories();
$products = ProductDB::getProductsByCategory($category_id);
include('product_list.php');
} else if ($action == 'delete_product') {
$product_id = filter_input(INPUT_POST, 'product_id',
FILTER_VALIDATE_INT);
$category_id = filter_input(INPUT_POST, 'category_id',
FILTER_VALIDATE_INT);
ProductDB::deleteProduct($product_id);
header("Location: .?category_id=$category_id");
} else if ($action == 'show_add_form') {
$categories = CategoryDB::getCategories();
include('product_add.php');
C14, Slide 40
The index.php file (continued)
} else if ($action == 'add_product') {
$category_id = filter_input(INPUT_POST, 'category_id',
FILTER_VALIDATE_INT);
$code = filter_input(INPUT_POST, 'code');
$name = filter_input(INPUT_POST, 'name');
$price = filter_input(INPUT_POST, 'price');
if ($category_id == NULL || $category_id == FALSE ||
$code == NULL ||
$name == NULL || $price == NULL || $price == FALSE) {
$error = "Invalid product data. Check all fields and try
again.";
include('../errors/error.php');
} else {
$category = CategoryDB::getCategory($category_id);
$product = new Product($category, $code, $name, $price);
ProductDB::addProduct($product);
header("Location: .?category_id=$category_id");
}
}
?>
C14, Slide 41
The product_list.php file
<?php include '../view/header.php'; ?>
<main>
<h1>Product List</h1>
<aside>
<!-- display a list of categories -->
<h2>Categories</h2>
<nav>
<ul>
<?php foreach ($categories as $category) : ?>
<li>
<a href="?category_id=<?php echo $category->getID();
?>">
<?php echo $category->getName(); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</aside>
C14, Slide 42
The product_list.php file (continued)
<section>
<!-- display a table of products -->
<h2><?php echo $current_category->getName(); ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th class="right">Price</th>
<th> </th>
</tr>
C14, Slide 43
The product_list.php file (continued)
<?php foreach ($products as $product) : ?>
<tr>
<td><?php echo $product->getCode(); ?></td>
<td><?php echo $product->getName(); ?></td>
<td class="right"><?php echo
$product->getPriceFormatted(); ?>
</td>
<td><form action="." method="post"
id="delete_product_form">
<input type="hidden" name="action"
value="delete_product">
<input type="hidden" name="product_id"
value="<?php echo $product->getID(); ?>">
<input type="hidden" name="category_id"
value="<?php echo
$current_category->getID(); ?>">
<input type="submit" value="Delete">
</form></td>
</tr>
<?php endforeach; ?>
</table>
C14, Slide 44
The product_list.php file (continued)
<p><a href="?action=show_add_form">Add Product</a></p>
</section>
</main>
<?php include '../view/footer.php'; ?>
C14, Slide 45
The syntax for looping
through an object’s properties
foreach($objectName as
[ $propertyName => ] $propertyValue) {
// statements to execute
}
C14, Slide 46
An Employee class
class Employee {
public $firstName, $lastName;
private $ssn, $dob;
C14, Slide 47
An Employee object with four properties
$employee = new Employee('John', 'Doe');
$employee->setSSN('999-14-3456');
$employee->setDOB('3-15-1970');
C14, Slide 48
The syntax for cloning an object
clone $objectName
An object to clone
$brass = new Category(4, 'Brass');
$trumpet = new Product($brass,
'Getzen', 'Getzen 700SP Trumpet', 999.95);
$trombone->setPrice(699.95);
// changes the price for both variables
C14, Slide 49
Create a clone of the object
$trombone = clone $trumpet;
// copy the object
$trombone->setPrice(899.95);
// only changes the price for trombone
C14, Slide 50
Using the == operator to compare objects
$result_1 = ($trumpet == $trombone);
// $result_1 is FALSE
$trumpet_2 = $trumpet;
$result_4 = ($trumpet === $trumpet_2);
// $result_4 is TRUE
C14, Slide 51
Key terms
clone
shallow copy
C14, Slide 52
Functions for inspecting an object
class_exists($class)
get_class($object)
is_a($object, $class)
property_exists($object, $property)
method_exists($object, $method)
C14, Slide 53
Determine if an object is an instance of a class
if (is_a($trumpet, 'Product')) {
// Code to work with a Product object
}
C14, Slide 54
Key terms
introspection
reflection
C14, Slide 55
A superclass
class Person {
private $firstName, $lastName, $phone, $email;
C14, Slide 56
A superclass (continued)
public function getEmail()
{ return $this->email; }
public function setEmail($value)
{ $this->email = $value; }
}
C14, Slide 57
A subclass
class Employee extends Person {
private $ssn, $hireDate;
// Finish initialization
parent::__construct($first, $last);
}
C14, Slide 58
Code that uses the subclass
$emp = new Employee(
'John', 'Doe', '999-14-3456', '8-25-1996');
$emp->setPhone('919-555-4321');
// Inherited from Person Class
C14, Slide 59
Key terms
inheritance
inherit
subclass, derived class, child class
superclass, base class, parent class
extend a superclass
override a method of a superclass
C14, Slide 60
How the access modifiers work
C14, Slide 61
A superclass
class Person {
protected $firstName, $lastName;
private $phone, $email;
A subclass
class Employee extends Person {
private $ssn, $hireDate;
C14, Slide 62
An abstract class with an abstract method
abstract class Person {
private $firstName, $lastName, $phone, $email;
// An abstract method
abstract public function getFullName();
}
C14, Slide 63
Implementing an abstract class
class Customer extends Person {
private $cardNumber, $cardType;
C14, Slide 64
Implementing an abstract (continued)
// Concrete implementation of the abstract method
public function getFullName() {
return $this->getFirstName() . ' ' .
$this->getLastName();
}
}
C14, Slide 65
Code that attempts to create an object
from the abstract class
$customer = new Person('John', 'Doe');
// Fatal error
C14, Slide 66
Key terms
abstract class
abstract method
concrete class
C14, Slide 67
A class with a final method
class Person {
// Other properties and methods not shown here
C14, Slide 68
A final class that can’t be inherited
final class Employee extends Person {
// Properties and methods for class
}
C14, Slide 69
The syntax for creating an interface
interface interfaceName {
const constantName = constantValue;
public function methodName( parameterList );
}
C14, Slide 70
An interface that provides three constants
interface EyeColor {
const GREEN = 1;
const BLUE = 2;
const BROWN = 3;
}
C14, Slide 71
A class that inherits a class
and implements an interface
class Employee extends Person implements Showable {
// get and set methods
C14, Slide 72
A class declaration that implements
three interfaces
class Customer extends Person
implements Showable,
Testable,
EyeColor { ... }
C14, Slide 73
Key terms
interface
implementing an interface
C14, Slide 74