This article mainly introduces the PHP design mode in the adapter model, interested in the reference of friends, I hope to be helpful to everyone.
Goal:
The interface of one class can be converted into another interface that the customer wants, so that the incompatible interface can work together. The popular understanding is to adapt the different interfaces into a unified API interface.
Role:
Target, which defines which interface the other classes are converted to, which is our desired interface.
Adaptee is the interface that needs to be adapted.
Adapter adapter, the other two roles are already existing roles, and the adapter role needs to be newly established, it is used to adapt the Adaptee and target interface.
Application Scenarios:
If the data operation has MySQL, Mysqli, PDO, SQLite, PostgreSQL, etc., if the build environment needs to replace the database, you can use the adapter mode unified interface. The same is true of the cache scenario, which is more convenient to replace the caching strategy (Memcache, Redis, APC).
Advantage:
The adapter is used by the adaptor to complete the adaptation target to achieve the purpose of transparent to the customer.
Example code:
Adaptation target, the specified interface will be implemented interface idatabase{public function Connect ($host, $username, $password, $database); Public Function query ($sql);} Adapter class Mysql implements idatabase{ protected $connect; Public function Connect ($host, $username, $password, $database) { $connect = mysql_connect ($host, $username, $ password); mysql_select_db ($database, $connect); $this->connect = $connect; //... } Public Function Query ($sql) {/ /...}}//Adapter class Postgresql implements idatabase{ protected $ Connect; Public function Connect ($host, $username, $password, $database) { $this->connect = Pg_connect ("host=$ Host dbname= $database user= $username password= $password "); //... } Public Function Query ($sql) { //... }} The client uses $client = new Postgresql (); $client->query ($sql);
Above
Target adapter: Idatabase interface
Adaptee: Database manipulation functions for MySQL and PostgreSQL
Adapter adapters: MySQL class and PostgreSQL class
Summary : The above is the entire content of this article, I hope to be able to help you learn.
Related recommendations:
How PHP Gets the file MIME type
How PHP operates a database to determine if a table exists
PHP operation MySQL Database and Session dialog method