Example: Interfaces
by designing a few objects that will be a part of a fictitious web application for home-automation (one of
my favorite hobbies). We want to build a web interface to control our various home devices (i.e. lights,
toaster, stereo). However, not all of our devices speak the same language, or protocol. While the X-10 protocol
still dominates the market, we find several other home-automation protocols creeping in. The four major
contenders among home-automation protocols are:
- X-10
- LONworks
- CEBus (EIA IS-60)
- Smart House
common control functionality exists: (1) turning on a device, (2) turning off a device, and (3) getting the
status of a device. Our interface will provide a template for this common functionality. We’ll name our
interface Control. As you can see, the methods do not contain any code.
<?php
class Control
{
function on() {}
function off() {}
function getStatus() {}
}
?>
understanding of what behavior is expected. Therefore, we’ll update our example with appropriate comments.
<?php
/*
* Class: Control
* Type: Interface
*
* Purpose: A template for common control functionality
* of home automated devices.
*
* Methods: on()
* off()
* getStatus()
*
* Error Codes
* -----------
* 0 - No errors occurred during transmission.
* 1 - An error occurred during transmission.
*
*
* API Developers
* --------------
* Be sure to provide appropriate functionality for each
* method. The application will dynamically instantiate
* the appropriate protocol for a selected device, and will
* expect consistent control functionality.
*/
class Control
{
function Control()
{
/*
* Do not allow instantiation of Control class.
* Prevent non subclass from calling constructor.
*/
if ( !is_subclass_of($this, "Control") ) {
trigger_error("Control instantiation from non subclass.", E_USER_ERROR);
return NULL;
}
}
function on() {} // Turn on a device.
function off() {} // Turn off a device.
function getStatus() {} // Get the status of a device.
}
?>
since it is the most popular one. We will inherit from Control, and provide the appropriate
implementation in X10_Control.