search
HomeBackend DevelopmentPHP Tutorial PHP 兑现适配器(Adapter)模式

PHP 实现适配器(Adapter)模式

适配器模式核心思想:把对某些相似的类的操作转化为一个统一的“接口”(这里是比喻的说话)--适配器,或者比喻为一个“界面”,统一或屏蔽了那些类的细节。适配器模式还构造了一种“机制”,使“适配”的类可以很容易的增减,而不用修改与适配器交互的代码,符合“减少代码间耦合”的设计原则。

??? 以下示例,用接近伪码的 PHP 语法,演示了一个数据库操作的适配器类,它可以操作 MySQL 和 Oracle 数据库,但使用了相同的方法。由于使用了适配器(Adapter)模式,我们不必关心 MySQL 和 Oracle 数据库操作类的不同。

??? 我们还可以方便的添加进 SQLite 等数据库操作的类,“插入”适配器中,立即就可以用操作 MySQL 和 Oracle 相同的方法来操作 SQLite 数据库了。

??? //适配器类:
??? //定义了4个操作所有数据库的方法

<?php
class Db_adapter {
	private $db;
	
	function __construct($db_obj) {
		$this->db = $db_obj;
	}
	
	function select_record() {
		$this->db->select ();
	}
	
	function insert_record() {
		$this->db->insert ();
	}
	
	function update_record() {
		$this->db->update ();
	}
	
	function delete_record() {
		$this->db->delete ();
	}
}

//MySQL 数据库操作类:
class Mysql {
	private $obj_mysql;
	
	function __construct() {
        $obj_mysql = ......
		
		;
	}
	
	function select() {
		$obj_mysql->mysql_select ();
	}
	
	function insert() {
		$obj_mysql->mysql_insert ();
	}
	
	function update() {
		$obj_mysql->mysql_update ();
	}
	
	function delete() {
		$obj_mysql->mysql_delete ();
	}
}

//Oracle 数据库操作类:
class Oracle {
	private $obj_oracle;
	
	function __construct() {
        $obj_oracle = ......
		
		;
	}
	
	function select() {
		$obj_oracle->oracle_select ();
	}
	
	function insert() {
		$obj_oracle->oracle_insert ();
	}
	
	function update() {
		$obj_oracle->oracle_update ();
	}
	
	function delete() {
		$obj_oracle->oracle_delete ();
	}
}

    //操作 MySQL 数据库:
    $obj = new Db_adapter(new Mysql())
	$obj->select_record ();
	$obj->insert_record ();
	$obj->update_record ();
	$obj->delete_record ();

    //操作 Oracle 数据库:
    $obj = new Db_adapter(new Oracle())
	$obj->select_record ();
	$obj->insert_record ();
	$obj->update_record ();
	$obj->delete_record ();
?>

???? 要求:MySQL、Oracle 类,有相同名字、相同个数的方法。方法内部实现了各自的操作数据库的代码。转换就是在这里完成的。
??? 增加新的数据库操作:构造新的类,有相同名字、相同个数的方法。方法内部实现不被关心(被屏蔽) - 不同的数据库实现不同。
??? 小缺点:新的类,可能因为疏忽,导致方法名字不合要求、个数不同。
??? 为了减少出错的可能,可以改进一下。方法就是定义一个接口,作为模板来继承,达到规范化。

??? db_adapter 类里的方法,只需要使用 interface db_driver 里函数即可。

<?php
//定义一个接口,
interface Db_driver {
	function select();
	function insert();
	function update();
	function delete();
}

// 数据库操作类,比如 MySQL,Oracle 必须实现 db_driver 接口的同名方法,从而进行了规范。
class Mysql implements Db_driver {
	private $obj_mysql;
	
	function __construct() {
        $obj_mysql = ......
		;
	}

	//这里省略的代码同前边的 MySQL 类
}

class Oracle implements Db_driver {
	private $obj_oracle;
	
	function __construct() {
        $obj_oracle = ......
		;
	}

	//这里省略的代码同前边的 Oracle 类
}
?>
?
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software