Index
    Preface
      What This Book Is About
      What You Need to Know
      How This Book Is Organized
      How to Use This Book
      Conventions Used in This Book
      Using Code Examples
      How to Contact Us
      Web Site and Code Examples
      Acknowledgments
      Chapter 1.  Database Applications and the Web
      Section 1.1.  The Web
      Section 1.2.  Three-Tier Architectures
      Chapter 2.  The PHP Scripting Language
      Section 2.1.  Introducing PHP
      Section 2.2.  Conditions and Branches
      Section 2.3.  Loops
      Section 2.4.  Functions
      Section 2.5.  Working with Types
      Section 2.6.  User-Defined Functions
      Section 2.7.  A Working Example
      Chapter 3.  Arrays, Strings, and Advanced Data Manipulation in PHP
      Section 3.1.  Arrays
      Section 3.2.  Strings
      Section 3.3.  Regular Expressions
      Section 3.4.  Dates and Times
      Section 3.5.  Integers and Floats
      Chapter 4.  Introduction to Object-Oriented Programming with PHP 5
      Section 4.1.  Classes and Objects
      Section 4.2.  Inheritance
      Section 4.3.  Throwing and Catching Exceptions
      Chapter 5.  SQL and MySQL
      Section 5.1.  Database Basics
      Section 5.2.  MySQL Command Interpreter
      Section 5.3.  Managing Databases and Tables
      Section 5.4.  Inserting, Updating, and Deleting Data
      Section 5.5.  Querying with SQL SELECT
      Section 5.6.  Join Queries
      Section 5.7.  Case Study: Adding a New Wine
      Chapter 6.  Querying Web Databases
      Section 6.1.  Querying a MySQL Database Using PHP
      Section 6.2.  Processing User Input
      Section 6.3.  MySQL Function Reference
      Chapter 7.  PEAR
      Section 7.1.  Overview
      Section 7.2.  Core Components
      Section 7.3.  Packages
      Chapter 8.  Writing to Web Databases
      Section 8.1.  Database Inserts, Updates, and Deletes
      Section 8.2.  Issues in Writing Data to Databases
      Chapter 9.  Validation with PHP and JavaScript
      Section 9.1.  Validation and Error Reporting Principles
      Section 9.2.  Server-Side Validation with PHP
      Section 9.3.  JavaScript and Client-Side Validation
      Chapter 10.  Sessions
      Section 10.1.  Introducing Session Management
      Section 10.2.  PHP Session Management
      Section 10.3.  Case Study: Using Sessions in Validation
      Section 10.4.  When to Use Sessions
      Section 10.5.  PHP Session API and Configuration
      Chapter 11.  Authentication and Security
      Section 11.1.  HTTP Authentication
      Section 11.2.  HTTP Authentication with PHP
      Section 11.3.  Form-Based Authentication
      Section 11.4.  Protecting Data on the Web
      Chapter 12.  Errors, Debugging, and Deployment
      Section 12.1.  Errors
      Section 12.2.  Common Programming Errors
      Section 12.3.  Custom Error Handlers
      Chapter 13.  Reporting
      Section 13.1.  Creating a Report
      Section 13.2.  Producing PDF
      Section 13.3.  PDF-PHP Reference
      Chapter 14.  Advanced Features of Object-Oriented Programming in PHP 5
      Section 14.1.  Working with Class Hierarchies
      Section 14.2.  Class Type Hints
      Section 14.3.  Abstract Classes and Interfaces
      Section 14.4.  Freight Calculator Example
      Chapter 15.  Advanced SQL
      Section 15.1.  Exploring with SHOW
      Section 15.2.  Advanced Querying
      Section 15.3.  Manipulating Data and Databases
      Section 15.4.  Functions
      Section 15.5.  Automating Querying
      Section 15.6.  Table Types
      Section 15.7.  Backup and Recovery
      Section 15.8.  Managing Users and Privileges
      Section 15.9.  Tuning MySQL
      Chapter 16.  Hugh and Dave's Online Wines:A Case Study
      Section 16.1.  Functional and System Requirements
      Section 16.2.  Application Overview
      Section 16.3.  Common Components
      Chapter 17.  Managing Customers
      Section 17.1.  Code Overview
      Section 17.2.  Customer Validation
      Section 17.3.  The Customer Form
      Chapter 18.  The Shopping Cart
      Section 18.1.  Code Overview
      Section 18.2.  The Winestore Home Page
      Section 18.3.  The Shopping Cart Implementation
      Chapter 19.  Ordering and Shipping at the Online Winestore
      Section 19.1.  Code Overview
      Section 19.2.  Credit Card and Shipping Instructions
      Section 19.3.  Finalizing Orders
      Section 19.4.  HTML and Email Receipts
      Chapter 20.  Searching and Authentication in the Online Winestore
      Section 20.1.  Code Overview
      Section 20.2.  Searching and Browsing
      Section 20.3.  Authentication
      Appendix A.  Linux Installation Guide
      Section A.1.  Finding Out What's Installed
      Section A.2.  Installation Overview
      Section A.3.  Installing MySQL
      Section A.4.  Installing Apache
      Section A.5.  Installing PHP
      Section A.6.  What's Needed for This Book
      Appendix B.  Microsoft Windows Installation Guide
      Section B.1.  Installation Overview
      Section B.2.  Installing with EasyPHP
      Section B.3.  What's Needed for This Book
      Appendix C.  Mac OS X Installation Guide
      Section C.1.  Getting Started
      Section C.2.  Installing MySQL
      Section C.3.  Setting Up Apache and PHP
      Section C.4.  What's Needed for This Book
      Appendix D.  Web Protocols
      Section D.1.  Network Basics
      Section D.2.  Hypertext Transfer Protocol
      Appendix E.  Modeling and Designing Relational Databases
      Section E.1.  The Relational Model
      Section E.2.  Entity-Relationship Modeling
      Appendix F.  Managing Sessions in theDatabase Tier
      Section F.1.  Using a Database to Keep State
      Section F.2.  PHP Session Management
      Section F.3.  MySQL Session Store
      Appendix G.  Resources
      Section G.1.  Client Tier Resources
      Section G.2.  Middle-Tier Resources
      Section G.3.  Database Tier Resources
      Section G.4.  Security and Cryptography Resources
      Appendix H.  The Improved MySQL Library
      Section H.1.  New Features
      Section H.2.  Getting Started
      Section H.3.  Using the New Features
    Colophon
    Copyright



 

Previous Section  < Day Day Up >  Next Section

14.3 Abstract Classes and Interfaces

When developing class hierarchies, it's often useful to insert extra classes to help logically organize code or to provide a base for polymorphic behavior.

14.3.1 The abstract keyword

Abstract classes are available in PHP5.

In Example 14-1, we defined a set of related classes to describe shapes that includes a base class Shape and its two member functions color( ) and sides( ). Let's suppose we want to add a function area( ) that calculates the area of a shape. If we want to allow the area to be calculated for all Shape objects, then the function must be made available in the Shape class.

However, unlike the color( ) and sides( ) functions, the area( ) function can only be implemented in the descendant classes because area calculations vary from shape to shape. The area of a circle is calculated using the radius, while a rectangle uses height and width, and so on. Using the abstract keyword, PHP5 allows you to define member functions without having to define an implementation. However, a class that contains an abstract function can't be used to create objects, and must also be defined as abstract. Example 14-2 shows how the Shapes class is redefined to include the abstract area( ) function.

Example 14-2. An abstract base class
<?php



abstract class Shape

{

    var $color;

    var $sides;



    function color( ) 

    { 

        return $this->color; 

    }



    function sides( )

    {

        return $this->sides;

    }



    abstract function area( );



    function _  _construct($color, $sides)

    {

        $this->color = $color;

        $this->sides = $sides;

    }

}



class Circle extends Shape

{

    var $radius;



    function area( )

    {

        return 2 * pi( ) * $this->radius;

    }



    function _  _construct($color, $radius)

    {

        $this->radius = $radius;

        parent::_  _construct($color, 1);

    }

}



class Rectangle extends Shape

{

    var $width;

    var $height;



    function area( )

    {

        return $this->width * $this->height;

    }



    function _  _construct($color, $width, $height)

    {

        $this->width = $width;

        $this->height = $height;

        parent::_  _construct($color, 4);

    }

}



class Triangle extends Shape

{

    // The length of each side

    var $a;

    var $b;

    var $c;



    function area( )

    {

        // Area using Heron's formula

        $s = ($this->a + $this->b + $this->c)/2;

        $area = sqrt(

            $s * ($s - $this->a) * ($s - $this->b) * ($s - $this->c)

            );



        return $area;

    }



    function _  _construct($color, $a, $b, $c)

    {

        $this->a = $a;

        $this->b = $b;

        $this->c = $c;

        parent::_  _construct($color, 3);

    }

}

?>

Example 14-2 includes three classes—Circle, Rectangle, and Triangle—that extend the abstract Shape class and provide shape specific implementations of the abstract function area( ). (We have also removed the Polygon class and the angles( ) function to help simplify the example.)

The following fragment shows which classes from Example 14-2 can be used:

require 'example.14-2.php';



$t = new Triangle("yellow", 2, 3, 4);

$c = new Circle("blue", 5);

$r = new Rectangle("green", 2, 4);



print "Area of our triangle = {$t->area( )} sq units\n";

print "Area of our circle = {$c->area( )} sq units\n";

print "Area of our rectangle = {$r->area( )} sq units\n";



// The following line causes a fatal error because Shape is abstract

$s = new Shape("green", 5);

Before the fatal error caused by the attempt to create an object from the abstract class Shape, the previous example prints:

Area of our triangle = 2.9047375096556 sq units

Area of our circle = 31.415926535898 sq units

Area of our rectangle = 8 sq units

There are a few rules to observe when defining abstract classes and functions:

  • An abstract member function can't contain a body definition.

  • A class must be declared as abstract if it contains any abstract functions.

  • You can declare protected and public functions as abstract, however, it is an error to declare a private function as abstract.

  • Any descendant classes that don't implement an abstract function defined in a base class must also be declared as abstract.

14.3.2 Interfaces

Interfaces are available in PHP5.

Interfaces provide another way of describing functionality in a class hierarchy. An interface defines member functions without providing any implementation, and class definitions implement those functions. Interfaces are defined using the interface keyword, and class definitions use interfaces with the implements keyword. An example is shown in Example 14-3:

Example 14-3. Using Interfaces
<?php



interface Audible

{

    function sound( );

}



class Animal implements Audible

{

    var $name;

    var $says;

    var $legs;



    function sound( )

    {

        return $this->says;

    }



    function name( )

    {

        return $this->name;

    }



    function numberOfLegs( )

    {

        $this->legs;

    }



    function _  _construct($name, $says, $legs)

    {

        $this->name = $name;

        $this->says = $says;

        $this->legs = $legs;

    }

}

?>

The Audible interface defined in Example 14-3 acts like an abstract base class for the Animal class: you can't create Audible objects directly, but an Animal object can be used as if it were an Audible object. Classes that specify an interface with the implements keyword must implement all the functions from the interface.

Interfaces are useful for implementing polymorphic behavior and are commonly used to relate classes that otherwise would not be related. For example, a Trumpet class wouldn't necessarily be related to the Animal class, however we may want to generically process objects from both classes as Audible:

// access to the Audible interface

require "example.14-3.php";



class Trumpet implements Audible

{

    function sound( )

    {

        return "Toot";

    }



    // Other functions that support a Trumpet 

    // ...

    function orchestraSection( )

    {

        return "Brass";

    }

}

To further illustrate the point, we can implement the sound( ) function for the Triangle class we defined earlier:

// access to the Shape class

require "example.14-1.php";



// access to the Audible interface

require "example.14-3.php";



class Triangle extends Shape implements Audible

{

    // The length of each side

    var $a;

    var $b;

    var $c;



    function sound( )

    {

        return "Ding";

    }



    function area( )

    {

        // Area using Heron's formula

        $s = ($this->a + $this->b + $this->c)/2;

        $area = sqrt(

            $s * ($s - $this->a) * ($s - $this->b) * ($s - $this->c)

            );



        return $area;

    }



    function _  _construct($color, $a, $b, $c)

    {

        $this->a = $a;

        $this->b = $b;

        $this->c = $c;

        parent::_  _construct($color, 3);

    }

}

Now Animal, Trumpet, and Triangle objects can all be treated as Audible objects:

// Create an empty array to hold some objects

$things = array( );



// Add some objects



// An Animal is constructed with a name, sound, and leg count

$things[] = new Animal("Cow", "Moo", 4);



// A Trumpet is constructed without any parameters

$things[] = new Trumpet;



// A Triangle is constructed with a color, and the 

// length of the three sides

$things[] = new Triangle("Silver", 3, 3, 3);



// A Circle is constructed with a color and a radius

$things[] = new Circle("Blue", 5);



// Check out the sound

foreach ($things as $t)

{

    if ($t instanceof Audible)

        print $t->sound( );

}

Interfaces also provide a mechanism for exposing subsets of a class's functionality. When a Triangle is being used as an Audible object, we only care about the sound( ) member function. The code in the above example would still work even if we change the names of the other Triangle member functions: because Triangle implements Audible, we can be sure that a Triangle can be used as an Audible object.

Functions can intentionally limit how an object is used using class type hints. Consider a function that works with Audible objects:

// return a formatted string to represent sound

function showSound(Audible $obj)

{

    return "!! {$obj->sound( )} !!";

}

The function showSound( ) can only use $obj parameter if it's an Audible object because the parameter is declared as Audible. An interface acts like a contract: classes that implement an interface are guaranteed to support a defined set of functions, while users of an interface warrant only to use those functions.

PHP allows multiple interfaces to be implemented in a class definition by including a comma-separated list of interface names after the implements keyword. This allows a class definition to use interfaces to formally describe how it can be used in different circumstances. We have shown how several different classes can implement the Audible interface; we can just as easily add other interfaces such as a WebDisplayable interfaces that defines functions for rendering the object as HTML. Of course, each class that implements an interface must support the functions it describes.

    Previous Section  < Day Day Up >  Next Section







    Copyright © 2010 | Domen maybe sale - bye this domen