Home > Article > Backend Development > PHP design pattern - Adapter pattern Adapter
In your application, you may be using a documented code base, however, we often need to add new functionality that requires using existing objects in different ways. Maybe the new feature just needs a different name, or maybe the new feature needs slightly different behavior than the original object.
To solve the above problems, using adapter mode is a good solution. Use the adapter pattern to create another object. This Adapterobject acts as an intermediary between the original application and the new functionality. The adapter design pattern simply adapts the interface of a certain object to the interface expected by another object .
Code example:
class errorObject{ private $_error; public function __construct($error){ $this->_error = $error; } public function getError(){ return $this->_error; } } class logToConsole{ private $_errorObject; public function __construct($errorObject){ $this->_errorObject = $errorObject; } public function write(){ fwrite(STDERR, $this->_errorObject->getError()); } } $error = new errorObject("404:Not Found"); $log = new logToConsole($error); $log->write();
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 address this problem, we can adopt the following two solutions:
● Create the errorObject class of the existing code base;
● Create an Adapter class;
Considering the need to maintain the standardization of these public interfaces, creating an Adapter object is the best solution.
The functionality of the existing errorObject must be present in the newly created adapter object, and the getErrorNumber() and getErrorText() methods must be valid.
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; } } $error = new logToCSVAdapter("404:Not Found"); $log = new logToCSV($error); $log->write();
General usage scenarios of adapter mode:
● Database driver (you can view the source code of the driver part of each framework)
● webservices (use adapters in multiple different webservices)
The above has introduced the PHP design pattern - Adapter pattern, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.