PHP SOAP and REST at Web Service(ウェブサービスでのSOAPとREST)
■SOAP
自サーバにない(所有していない)プログラムのメソッドを呼び出す、リモートプロシージャコール(遠隔呼び出し)のためのプロトコル。相手側がアクセス可能にしているメソッドならばアクセスが可能である。但し、PHPでSOAPを使用するには、インストール時に–enable-soapされていなければならない。
ウェブサービスへのアクセス
以下のようにするとGoogle検索のウェブサービスを利用することができる。
<?php
try {
$client = new SoapClient('http://api.google.com/GoogleSearch.wsdl');
$results = $client->doGoogleSearch($key, $query, 0, 10, false, '', false, '', '', '');
foreach($results->resultElements as $result){
print('<a href=">' . htmlentities($result->URL, ENT_QUOTES) . '">');
print(htmlentities($result->title, ENT_COMPAT));
print('</a>');
}
}
catch(SoapFault $e){
$e->getMessage();
}
?>
SoapClientについて
- Googleに提供されたWSDLファイルに基づきSOAPクライアントを生成する
- SoapClientは失敗すると例外をスローする
WSDLについて
- WSDLファイルとは、「提供されている場所」や「メッセージの形式」「プロトコル」「メソッド」など、サービスの具体的内容が記述されている
- WSDLファイルを使用しない場合は、SoapClientの第一引数にnullを、第二引数でウェブサービスのエントリーポイントのURIを指定しなければならない
デバッグ
SOAPクライアントは、SOAPサーバに送受信したメッセージを用いてデバッグするために特別なメソッドを備えている。但し、使用するためにはSoapClientの第二引数でtraceを1に設定しなければならない。以下のようにすると、生の通信を見ることができる。
<?php
$cleint = new SoapClient(
'http://api.google.com/GoogleSearch.wsdl',
array(
'trace' => 1
)
);
$results = $client->doGoogleSearch($key, $query, 0, 10, false, '', false, '', '', '');
print($results->__getLastRequestHeaders());
print($result->__getLastRequest());
/*
POST /search/beta2 HTTP/1.1
Host: api.google.com
Connection: Keep-Alive
User-Agent: PHP SOAP 0.1
Connect-Type: text/xml; charset=utf-8
SOAPAction: "url:GoogleSearchAction"
Content-Length: 900
<?xml version="1.0" encoding="UTF-8"?>
...
*/
?>
SOAPサーバの作り方
以下のように、SOAPサーバの挙動を定義する。
<?php
class MySoapServer {
public function getMessage(){
return 'Hello, World!';
}
public function addNumbers($num1, $num2){
return (int)$num1 + (int)$num2;
}
}
?>
以下のように、定義したクラスを実際にSoapServerとして設定する。
<?php
require_once('MySoapServer.class.php');
$server = new SoapServer(
null,
array(
'uri' => 'http://sample.org/soap/server'
)
);
$server->setClass('MySoapServer');
$server->handle();
?>
以上のような場合、クライアント側のコードは以下のようになる。
<?php
$client = new SoapClient(
null,
array(
'location' => 'http://sample.org/soap/server/server.php',
'uri' => 'http://sample.org/soap/server/',
)
);
print($client->getMessage());//Hello, World!
print($client->addNumbers(1,8));//9
?>
■REST
RESTはプロトコルではなく、ウェブサービスの設計思想の一つである。個々のリソースはURIにおいて参照することができる。
<?php
$user = 'john';
$pass = 'password';
$tag = htmlentities($_POST['tag'], ENT_QUOTES);
$req = "https://{$user}:{$pass}@api.del.icio.us/v1/posts/all?tag={$tag}";
$bookmarks = new SimpleXMLElement($req, null, true);
foreach($bookmarks as $bookmark){
print('<a href="' . htmlentities($bookmark['href'], ENT_QUOTES) . '">');
print(htmlentities($bookmark['description'], ENT_COMPAT));
print('</a>');
}
?>
TrackBack URL :
Comments (0)