Design Patterns Reference: Adapter

“The Adapter Design Pattern simply adapts one object’s interfaces to what another object expects.”

/**
* Example Adapter Class
*/

/**
* original object
*/

class errorObject
{
private $__error;

public function __construct($error)
{
$this->__errorĀ  = $error;
}

public function getError()
{
return $this->__error;
}
}

/**
* original Log class
*/

class logToConsole
{
private $__errorObject;

public function __construct($errorObject)
{
$this->__errorObject = $errorObject;
}

public function write()
{
fwrite(STDERR, $this->__errorObject->getError());
}
}

/**
* Initial way to utilize this system
* create the new 404 error object
*/

$error = new errorObject(“404:Not Found”);

/** then write the error to the console **/

$log = new logToConsole($error);
$log->write();

/**
* extend the logging functionality
* to log to CSV file instead
* with the log # and text
*/

class logToCSV
{
const CSV_LOCATION = ‘log.csv’;

private $__errorObject;

public function __construct($errorObject)
{
$this->__errorObject = $errorObject;
}

public function write()
{
$line = $this->__errorObject->getErrorNumber();
$line .= ‘,’;
$line .= $this->__errorObject->getErrorText();
$line .= “\n”;

file_put_contents(self::CSV_LOCATION, $line, FILE_APPEND);
}
}

/**
* to use the new log
* original errorObject must either be changed
* or better, extended
*/

class logToCSVAdapter extends errorObject
{
private $__errorNumber, $__errorText;

public function __construct($error)
{
parent::__construct($error);

$parts = explode(‘:’, $this->getError());

$this->__errorNumber = $parts[0];
$this->__errorText = $parts[1];
}

public function getErrorNumber()
{
return $this->__errorNumber;
}

public function getErrorText()
{
return $this->__errorText;
}
}

/**
* new way to implement the system extended
* create the new 404 error object adapted for csv
*/

$error = new logToCSVAdapter(“404:Not Found”);

/** then write the error to the csv file **/
$log = new logToCSV($error);
$log->write();

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

Comments are closed.