如何在PHP中为SOAP API实现Fluent Interface并简化重复调用?
解决PHP SOAP API重复调用的流畅接口实现及动态方法处理
一、用__call魔术方法消除重复代码
你不需要单独写通用方法,PHP的__call魔术方法正好能解决这个问题——当调用类中不存在的公共方法时,该方法会自动触发,完美替代那些重复的getFacilityIds、getFacilityInformation类方法。
直接替换现有重复代码,实现如下:
class SoapClientWrapper { private $client; private $sessionKey; public function __construct($client, $sessionKey) { $this->client = $client; $this->sessionKey = $sessionKey; } // 魔术方法:处理所有未定义的方法调用 public function __call($methodName, $arguments) { // 构造参数:默认带上sessionKey,同时合并传入的额外参数 $params = array_merge( ['sessionKey' => $this->sessionKey], $arguments ? $arguments[0] : [] ); return $this->client->__soapCall($methodName, [$params]); } }
使用方式
现在直接调用任何SOAP接口对应的方法名即可,示例:
$wrapper = new SoapClientWrapper($yourSoapClient, $sessionKey); // 调用getFacilityIds $facilityIds = $wrapper->getFacilityIds(); // 调用带额外参数的接口,比如getUserInfo需要userId $userInfo = $wrapper->getUserInfo(['userId' => 123]);
二、实现流畅接口(Fluent Interface)
要实现流畅接口,只需让__call方法按需返回当前对象即可——适合不需要返回接口数据的操作,或者你可以区分方法类型:
public function __call($methodName, $arguments) { $params = array_merge( ['sessionKey' => $this->sessionKey], $arguments ? $arguments[0] : [] ); // 针对无返回值的操作,执行后返回$this以支持链式调用 if (in_array($methodName, ['initSession', 'refreshToken'])) { $this->client->__soapCall($methodName, [$params]); return $this; } // 普通方法返回接口数据 return $this->client->__soapCall($methodName, [$params]); }
流畅调用示例
$wrapper->initSession() ->refreshToken(['token' => 'xxx']) ->getFacilityInformation();
三、额外优化:方法存在性校验
为避免调用完全不存在的SOAP方法,可以提前通过客户端获取所有可用方法并校验:
public function __call($methodName, $arguments) { // 获取SOAP服务的所有可用方法并解析出方法名 $availableMethods = array_map(function($func) { return explode(' ', $func)[1]; }, $this->client->__getFunctions()); if (!in_array($methodName, $availableMethods)) { throw new BadMethodCallException("SOAP方法 {$methodName} 不存在"); } // 后续参数构造和调用逻辑... $params = array_merge( ['sessionKey' => $this->sessionKey], $arguments ? $arguments[0] : [] ); return $this->client->__soapCall($methodName, [$params]); }
内容的提问来源于stack exchange,提问作者Bradley
相关产品推荐
相关产品推荐

