Home Backend Development PHP Tutorial PHP design pattern - Adapter pattern Adapter

PHP design pattern - Adapter pattern Adapter

Jul 29, 2016 am 09:14 AM
error function public this

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();
Copy after login

If one day the requirements change, it is required to record errors into a CSV file. The format of CSV requires that the first column is the numerical error code and the second column is the error text. The new requirement has given code that implements logging, the problem is that the code is written based on another version of errorObject, which is different from the one currently used. The new errorObject class has two other methods named getErrorNumber() and getErrorText(), which are used by the logToCSV class:
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);
	}
}
Copy after login
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();
Copy after login

When you need to convert the interface of one object for another object, implementing Adapterobject is not only the best practice, but also can save a lot of trouble.

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.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to PHP Fatal error: Call to undefined method PDO::prepare() in Solution to PHP Fatal error: Call to undefined method PDO::prepare() in Jun 22, 2023 pm 06:40 PM

PHP is a popular web development language that has been used for a long time. The PDO (PHP Data Object) class integrated in PHP is a common way for us to interact with the database during the development of web applications. However, a problem that some PHP developers often encounter is that when using the PDO class to interact with the database, they receive an error like this: PHPFatalerror:CalltoundefinedmethodPDO::prep

What should I do if 'Uncaught (in promise) Error: Request failed with status code 500' occurs when using axios in a Vue application? What should I do if 'Uncaught (in promise) Error: Request failed with status code 500' occurs when using axios in a Vue application? Jun 24, 2023 pm 05:33 PM

It is very common to use axios in Vue applications. axios is a Promise-based HTTP client that can be used in browsers and Node.js. During the development process, the error message "Uncaught(inpromise)Error: Requestfailedwithstatuscode500" sometimes appears. For developers, this error message may be difficult to understand and solve. This article will explore this

Solve the problem of 'error: incomplete type is not allowed' in C++ code Solve the problem of 'error: incomplete type is not allowed' in C++ code Aug 26, 2023 pm 08:54 PM

Solve the "error:incompletetypeisnotallowed" problem in C++ code. During the C++ programming process, you sometimes encounter some compilation errors. One of the common errors is "error:incompletetypeisnotallowed". This error is usually caused by operating on an incomplete type. This article will explain the cause of this error and provide several solutions. firstly, I

Solve the 'error: expected initializer before 'datatype'' problem in C++ code Solve the 'error: expected initializer before 'datatype'' problem in C++ code Aug 25, 2023 pm 01:24 PM

Solve the "error:expectedinitializerbefore'datatype'" problem in C++ code. In C++ programming, sometimes we encounter some compilation errors when writing code. One of the common errors is "error:expectedinitializerbefore'datatype'". This error usually occurs in a variable declaration or function definition and may cause the program to fail to compile correctly or

0271: What should I do if the computer cannot be turned on due to real time clock error? 0271: What should I do if the computer cannot be turned on due to real time clock error? Mar 13, 2023 am 11:30 AM

Solution to "0271: real time clock error" that cannot boot: 1. Press F1, and in the interface that appears, move the option bar to the third item "Date/Time"; 2. Manually change the system time to the current one time; 3. Press F10 and select yes in the pop-up dialog box; 4. Re-open the notebook to boot normally.

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Solution to PHP Fatal error: Call to undefined function mysqli_connect() Solution to PHP Fatal error: Call to undefined function mysqli_connect() Jun 23, 2023 am 09:40 AM

When writing web applications using PHP, a MySQL database is often used to store data. PHP provides a way to interact with the MySQL database called MySQLi. However, sometimes when using MySQLi, you will encounter an error message, as shown below: PHPFatalerror:Calltoundefinedfunctionmysqli_connect() This error message means that PHP cannot find my

How to solve PHP Warning: fopen(): failed to open stream: No such file or directory How to solve PHP Warning: fopen(): failed to open stream: No such file or directory Aug 19, 2023 am 10:44 AM

How to solve PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectory In the process of using PHP development, we often encounter some file operation problems, one of which is "PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectory"

See all articles