Classmaps
在 PHP 中建立 SOAP 客戶端時,還可以在配置陣列中設定 classmap
金鑰。這個 classmap
定義了 WSDL 中定義的哪些型別應該對映到實際的類,而不是預設的 StdClass
。你希望這樣做的原因是因為你可以在這些類上自動完成欄位和方法呼叫,而不必猜測在常規 StdClass
上設定了哪些欄位。
class MyAddress {
public $country;
public $city;
public $full_name;
public $postal_code; // or zip_code
public $house_number;
}
class MyBook {
public $name;
public $author;
// The classmap also allows us to add useful functions to the objects
// that are returned from the SOAP operations.
public function getShortDescription() {
return "{$this->name}, written by {$this->author}";
}
}
$soap_client = new SoapClient($link_to_wsdl, [
// Other parameters
"classmap" => [
"Address" => MyAddress::class, // ::class simple returns class as string
"Book" => MyBook::class,
]
]);
配置類對映後,每當執行返回型別 Address
或 Book
的特定操作時,SoapClient 將例項化該類,用資料填充欄位並從操作呼叫返回它。
// Lets assume 'getAddress(1234)' returns an Address by ID in the database
$address = $soap_client->getAddress(1234);
// $address is now of type MyAddress due to the classmap
echo $address->country;
// Lets assume the same for 'getBook(1234)'
$book = $soap_client->getBook(124);
// We can not use other functions defined on the MyBook class
echo $book->getShortDescription();
// Any type defined in the WSDL that is not defined in the classmap
// will become a regular StdClass object
$author = $soap_client->getAuthor(1234);
// No classmap for Author type, $author is regular StdClass.
// We can still access fields, but no auto-completion and no custom functions
// to define for the objects.
echo $author->name;