Datasheet

DESIGN PATTERNS IN WEB FRAMEWORKS
x
17
private static $isRented = FALSE;
private function __construct() {
}
static function rentCar() {
if (FALSE == self::$isRented ) {
if (NULL == self::$car) {
self::$car= new CarSingleton();
}
self::$isRented = TRUE;
return self::$car;
} else {
return NULL;
}
}
function returnCar(CarSingleton $carReturned) {
self::$isRented = FALSE;
}
function getMake() {return $this->make;}
function getModel() {return $this->model;}
function getMakeAndModel() {return $this->getMake().’ ‘.$this->getModel();}
}
?>
code snippet /singleton/CarSingleton.class.php
The class in the preceding code is a Singleton representing one concrete specimen of a Dodge
Magnum car in a car rental business. The
__construct() function is the constructor of this class.
Note that it is set to
private to prevent usage from outside of the class. The double underscore
indicates that
__construct() is one of the magic functions in PHP (special functions provided by
the language), and declaring the constructor in a class will override the default one.
CarSingleton does provide an interface for renting and returning the car as well as pretty obvi-
ous getters. The
rentCar() function checks fi rst whether the car is already rented. This is not part
of the Singleton pattern, but is important for the logic of our example. If the car wasn’t rented, the
function checks if the
$car variable is NULL before returning it. If it equals NULL, it is constructed
before the fi rst use. Thus,
rentCar() corresponds to the instance() method of the design pattern.
The
Customer class in the following example represents a person who uses the services of the car
rental business. He can rent the car (there is only one), return it, and tell the make and model of the
car, provided that he drives it at the moment.
<?php
include_once(‘CarSingleton.class.php’);
class Customer{
private $rentedCar;
private $drivesCar = FALSE;
function __construct() {
}
function rentCar() {
$this->rentedCar = CarSingleton::rentCar();
if ($this->rentedCar == NULL) {
$this->drivesCar = FALSE;
c01.indd 17c01.indd 17 1/24/2011 5:45:19 PM1/24/2011 5:45:19 PM