【发布时间】:2013-03-04 23:37:41
【问题描述】:
我想知道在一个 PHP 框架中实现两个类似 API 的好方法是什么?
我的想法是这样的:
- /vendors/wrapperA.php - 扩展父级,实现 API (A)
- /vendors/wrapperB.php - 扩展父级,实现 API (B)
- Parent.php - 唯一直接引用的脚本以使用 API 包装器
- $config[] 数组用于 Parent.php 中的配置
- index.php - 一个实现并且仅引用 Parent.php 的网站
假设 API 有很多方法,但我们只实现了两个简单的 API 调用:
- connect() - 创建到服务的连接。
- put() - 如果成功则返回一个“putID”。
由于 API (A) 和 API (B) 不同,这就是包装器通过抽象这两种方法来实现其实用程序的方式。
现在,我想说的是:
- 在 PHP 中实现此功能的好方法是什么?
- connect() 语句需要验证是否存在有效连接。
- put() 语句需要返回一个 ID
- 我们不想暴露 put 方法中的差异,它只需要根据我们是否正确配置 API 身份验证(无论是什么情况 - 通过密钥或其他方式)来工作
即
类似
<?php $parent = new Parent();
$parent->connect(); //connect to one or both API's.
$parent->put('foo'); //push foo to the API
?>
目前,我的所有代码都在 Parent.php 中。
在 Parent.php 中包含所有代码的问题
- 代码蔓延
- 缺少模块化插件,以防我添加第三个 API。
- 代码混淆 - 哪个 API 是哪个?
编辑:根据 Marin 的回答设计的解决方案
<?php
/*** Interface ***/
interface API_Wrapper {
function connect();
function put($file);
}
/*** API Wrappers ***/
class API_A_Wrapper implements API_Wrapper {
function connect() {}
function put($file) { print 'putting to API A.'; }
}
class API_B_Wrapper implements API_Wrapper {
function connect() {}
function put($file) { print 'putting to API B.'; }
}
/*** Factory ***/
class Factory {
public static function create($type){
switch ($type) {
case "API_A" :
$obj = new API_A_Wrapper();
break;
case "API_B" :
$obj = new API_B_Wrapper();
break;
}
return $obj;
}
}
/*** Usage ***/
$wrapperA = Factory::create("API_A");
$wrapperA->put('foo');
$wrapperB = Factory::create("API_B");
$wrapperB->put('foo');
【问题讨论】:
-
恕我直言。
Parent应该只是一个接口,最多是一个创建 WrapperA 或 WrapperB 对象的工厂......这样,你总是知道你有哪个类,并且接口保持不变。如果您出于某种原因需要一个类,请使用装饰器模式。 -
接口如何防止代码蔓延?我目前将我的代码放在 Parent.php 中。随着我添加更多的方法,我使用了一个 $this->framework 变量,它不会在很长时间内扩展。
-
据我了解,您正在尝试使用一个 API 来驱动其他几个 API,即。一个 API 可以同时映射到其他几个 API 的使用。对吗?
-
不是从本质上讲,不是。当需要可能完全不同的第三个 API 时,接口会有所帮助。如果 WrapperA 和 WrapperB 很相似,那么它们可能继承自同一个抽象类,该抽象类可以实现接口。老实说,我更关注 2 和 3,而
Parent显然是直接调用的;) -
@didierc 我应该澄清一下 - 更多的是一个包装两个 API 的框架。
标签: php frameworks wrapper