Datasheet
DESIGN PATTERNS IN WEB FRAMEWORKS
x
23
<?php
class CarDecorator {
protected $car;
protected $gearMessage;
protected $comfortMessage ;
public function __construct(Car $car_in) {
$this->car = $car_in;
$this->comfortMessage = $car_in->comfortMessage;
}
function drive() {
return ‘Accelerating. ‘ . $this->car->gearMessage .
‘ Driving comfort is ‘ . $this->comfortMessage;
}
}
class AutomaticTransmissionDecorator extends CarDecorator {
protected $decorator;
public function __construct(CarDecorator $decorator_in) {
$this->decorator= $decorator_in;
}
public function installAutomaticTransmission(){
$this->decorator->car->gearMessage = ‘Auto transmission shifts up.’;
}
}
class GPSDecorator extends CarDecorator {
protected $decorator;
public function __construct(CarDecorator $decorator_in) {
$this->decorator= $decorator_in;
}
public function installGPS(){
$this->decorator->comfortMessage= ‘very high.’;
}
}
?>
code snippet /decorator/CarDecorator.class.php
We can test these classes with the following code.
<?php
include_once(‘Car.class.php’);
include_once(‘CarDecorator.class.php’);
$car = new Car();
$decorator = new CarDecorator($car);
$transmission = new AutomaticTransmissionDecorator($decorator);
$gps = new GPSDecorator($decorator);
echo ‘Driving standard car: <br />’;
echo $car->drive().’<br />’;
$transmission->installAutomaticTransmission();
$gps->installGPS();
echo ‘Driving fully decorated car: <br />’;
echo $decorator->drive() . ‘<br />’;
c01.indd 23c01.indd 23 1/24/2011 5:45:20 PM1/24/2011 5:45:20 PM