问题描述
有人知道如何使用PHP中的内置SoapClient记录所有请求和响应吗?实际上,我可以使用SoapClient::__getLastRequest()
和SoapClient::__getLastResponse()
手动记录所有内容,但是我们的系统中有大量肥皂请求,因此我正在寻找其他可能性.
Does anyone know how to log all request and responses with the builtin SoapClient in PHP? I could in fact manually log everything with SoapClient::__getLastRequest()
and SoapClient::__getLastResponse()
But we have that much soap requests in our system that i'm looking other possibilities.
注意:我使用的是wsdl模式,因此无法使用将所有通道都隧穿到SoapClient::__soapCall()
的方法
Note: i'm using wsdl mode so using a method that tunnels all through to SoapClient::__soapCall()
isn't an option
推荐答案
我赞同Aleksanders和Stefans的建议,但不会继承SoapClient.相反,我将常规的SoapClient包装在装饰器中,因为日志记录并不是SoapClient的直接关注点.此外,松散耦合使您可以轻松地用UnitTests中的模拟替代SoapClient,因此您可以专注于测试日志记录功能.如果只想记录特定的呼叫,则可以添加一些逻辑,以通过$ action或您认为合适的任何内容过滤请求和响应.
I second Aleksanders and Stefans suggestion but would not subclass SoapClient. Instead I'd wrap the regular SoapClient in a decorator, because logging is not a direct concern of the SoapClient. In addition, the loose coupling lets you easily substitute the SoapClient with a mock in your UnitTests, so you can concentrate on testing the logging functionality. If you only want to log specific calls, you can add some logic that filters requests and responses by $action or anything you see fit.
编辑,因为Stefan建议添加一些代码,所以装饰器可能看起来像这样,尽管我不确定__call()方法(请参见Stefans注释)
Edit since Stefan suggested to add some code, the decorator would probably look something like this, although I am not sure about the __call() method (see Stefans comments)
class SoapClientLogger
{
protected $soapClient;
// wrapping the SoapClient instance with the decorator
public function __construct(SoapClient $client)
{
$this->soapClient = $client;
}
// Overloading __doRequest with your logging code
function __doRequest($request, $location, $action, $version, $one_way = 0)
{
$this->log($request, $location, $action, $version);
$response = $this->soapClient->__doRequest($request, $location,
$action, $version,
$one_way);
$this->log($response, $location, $action, $version);
return $response;
}
public function log($request, $location, $action, $version)
{
// here you could add filterings to log only items, e.g.
if($action === 'foo') {
// code to log item
}
}
// route all other method calls directly to soapClient
public function __call($method, $args)
{
// you could also add method_exists check here
return call_user_func_array(array($this->soapClient, $method), $args);
}
}
这篇关于在PHP中记录所有Soap请求和响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!