問題描述
有誰知道如何使用 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 的直接關注點.此外,松散耦合讓您可以輕松地用單元測試中的模擬替換 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 請求和響應的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!