php中工厂模式负责创建对象,适配器模式负责统一接口,两者结合使用时通常由工厂返回适配后的对象实例。具体做法是在工厂的创建逻辑中实例化适配器类,并将原始目标对象注入其中,这样调用方只需依赖统一的接口即可获取经过转换的服务。如果目标对象不存在或类型不匹配,工厂应抛出异常或返回null,确保调用端能感知错误。

Factory如何决定返回哪个Adapter
工厂通过判断输入参数或配置来决定实例化哪一个具体的适配器。例如根据数据库驱动类型(MySQL或PostgreSQL)选择对应的适配器类。工厂内部维护一个映射表或直接使用条件分支,将通用的请求转化为特定适配器的实例化调用。这种设计使得新增适配器时无需修改工厂的核心逻辑,只需注册新的适配器类即可。

<?php
interface DataProvider {
public function fetch(): array;
}
class MySQLSource {
public function query(): string { return "SELECT * FROM users"; }
}
class MySQLAdapter implements DataProvider {
private $source;
public function __construct(MySQLSource $source) {
$this->source = $source;
}
public function fetch(): array {
return ["sql" => $this->source->query()];
}
}
class Factory {
public static function create(string $type): DataProvider {
if ($type === 'mysql') {
return new MySQLAdapter(new MySQLSource());
}
throw new \InvalidArgumentException("Unknown type");
}
}
$provider = Factory::create('mysql');
print_r($provider->fetch());
?>
Adapter如何处理源对象的差异
适配器通过包装源对象并实现统一接口来消除差异。在PHP中,这通常意味着适配器持有源对象的引用,并在其方法中调用源对象的具体方法,同时调整返回值格式以符合调用方的期望。例如,源对象可能返回字符串SQL,而适配器将其转换为数组结构。这种转换逻辑封装在适配器内部,对工厂和调用方透明。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
立即学习“PHP免费学习笔记(深入)”;

<?php
// 假设还有一个 PostgreSQL 源
class PostgresSource {
public function executeQuery(): string { return "SELECT * FROM users"; }
}
class PostgresAdapter implements DataProvider {
private $source;
public function __construct(PostgresSource $source) {
$this->source = $source;
}
public function fetch(): array {
// 注意方法名不同,需要适配
return ["sql" => $this->source->executeQuery()];
}
}
class Factory {
public static function create(string $type): DataProvider {
if ($type === 'postgres') {
return new PostgresAdapter(new PostgresSource());
}
// ... 其他逻辑
throw new \InvalidArgumentException("Unknown type");
}
}
$provider = Factory::create('postgres');
print_r($provider->fetch());
?>
当源对象方法签名不一致时适配器如何映射
当源对象的方法签名与目标接口不一致时,适配器需要在内部进行参数转换或方法重命名。例如,源对象使用query()而接口要求fetch(),或者源对象返回单一值而接口要求数组。适配器通过在其实现中显式调用源对象的方法并转换结果来解决这个问题。这种映射关系是适配器模式的核心,它确保了上层代码不需要关心底层实现的细节。


















