Usage and Migration Guide for Twilio's PHP Helper Library 5.x
The Twilio PHP SDK has undergone significant changes from version 4.x to 5.x - we'll break down the major changes here to make migrating to the new version as painless as possible. If you're integrating Twilio in your PHP app for the first time, you can skip straight to the install page.
PHPバージョンの互換性
The 5.x version of the Twilio SDK is compatible with PHP versions 5.5 and higher. As of August 2016, it is recommended that you upgrade your applications to at least PHP 5.6 to receive the latest security updates.
Namespaces
The new SDK takes advantage of PHP namespaces for proper autoloading. This means classes are no longer prepended by "Services_" or contain long class names as they did in version 4.x of the SDK. After the 5.x SDK has been autoloaded, you will be able to use namespaces as in the following example.
<?php // Composer autoload file require_once '/path/to/vendor/autoload.php'; use Twilio\Rest\Client;
Utilityクラス(TwiMLの生成で利用、 やVideo・ClientでのAuthTokenの生成で利用) もこのようにリファクタリングされました。利用できる namespace についてはAPIリファレンスを参照してください。
REST APIリソースへのアクセス
REST APIリソースにアクセスする方法もヘルパーライブラリ 4.x系から5.x系で大きく変わりました。4.x系を使ってREST APIリソースにアクセスする際、中には効率的なネットワークリクエストとはいえないものもありました。本当は1つのリクエストで済むものを2~3のリクエストを出すことが時折ありました。新しい 5.x系のヘルパーライブラリは、以下2つのコンセプトで対処します。
- Resource Context: まだオペレーションされていないもの、ないしは取得されていないREST APIリソースへのリファレンス
- Resource Instance: APIから取得されたオペレーション済みのリソースの表現
以下、IP Messaging REST APIを使った例を見てみましょう。
<?php require '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; // Create REST API Client $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); // 1.) Service instance context $service = $client->ipMessaging->services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); // 2.) Channel context $channelContext = $service->channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); // 3.) Channel instance $channel = $channelContext->fetch(); echo $channel->friendlyName;
番号順に、このコードで起こっていることを噛み砕いてみます。
- まず "context" を作成します。これがオペレーションしたい IP Messageing サービスのインスタンスです。すでにこのインスタンスの SID はわかっているので、APIに対してHTTPリクエストは発生しません。
- API経由で取得したい IP Messageingチャンネルに対して、"context" を作成します。こちらもすでに SID はわかっているはずですので、HTTPリクエストは発生しません。
- 最後に fetch を使ってAPIからの channelリソースを返します。こうすることで、REST APIに対してHTTP GETを生成しているのです。戻ってきた $channel オブジェクトは、Twilioのバックエンドで取得したチャンネルのプロパティーが付加されています。
4.x系のヘルパーライブラリでは、このようなやり取りに2つのHTTPリクエストを発生させていました。1つはサービスのインスタンスを取得するため、もう1つはチャンネルを取得するためです。これらのメソッドコールを流れるようにチェインさせることもできます。
<?php require '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; // Create REST API Client $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); // All together now! $channel = $client->ipMessaging ->services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') ->channels('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') ->fetch(); echo $channel->friendlyName;
似たような方法でリソースの作成・削除する方法は、APIドキュメントにあるそれぞれのタイプのサンプルを参照してください。
リソースのリスティングとページング
APIから取得するリソースのリストは大体似たようなパターンです。ここでは "read"メソッドを使ってみます。
<?php require '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; // Create REST API Client $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); // Get a list of channels $channels = $client->ipMessaging ->services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') ->channels ->read(); // List ALL the channels foreach ($channels as $channel) { echo $channel->friendlyName; }
ページをまたいで結果を総なめにするには、"stream"メソッドを追加います。こうすると表示する結果がページサイズ(設定で1ページ1000までに変更可能)を越えても、結果すべてに至るまでループして総なめにしたイテレータが返ってきます。
<?php require '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; // Create REST API Client $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); // Get a stream of channels $channelStream = $client->ipMessaging ->services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') ->channels ->stream(); // List ALL the channels foreach ($channelStream as $channel) { echo $channel->friendlyName; }
APIに引数を渡す
"read" にクエリーパラメータを渡したり、"create" や "update" にパラメータを追加する方法が、4.x系と5.x系で違うことにお気づきでしょうか。すべてのユニバーサル必須パラメータは位置的です。他のパラメータ(2つのうちどちらかが渡ったりするような必須パラメータを含む、"Body" や "MediaUrl" のようなもの) についてはarrayで渡ります。
次の、SMSを送信するサンプルを考えてみます。(Messageリソースを作ります)まず、必須な引数は "To" の電話番号です。他にあと2つ必要な引数があります:
- "From" の電話番号 かMessagingServiceSidのどちらか
- "Body" と "MediaUrl" のうち両方か片方
これを実現するコードは以下の通りです。
<?php require_once '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; // Create a client with your Account SID and Auth Token from twilio.com/console $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); $client->messages->create( '+15558675309', array( 'from' => '+15017250604', 'body' => 'Hey Jenny! Good luck on the bar exam!', 'mediaUrl' => 'http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg', ) );
Here's an example of querying for calls that were completed between midnight July 4th, 2009 and midnight July 6th, 2009.
<?php require_once '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; // Create a client with your Account SID and Auth Token from twilio.com/console $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); // Read an array of calls from the REST API between two dates $calls = $client->calls->read( array( 'status' => 'completed', 'starttimeAfter' => '2009-07-04', 'starttimeBefore' => '2009-07-06' ) ); // Loop over the list of calls and echo a property for each one foreach ($calls as $call) { echo $call->to; }
TwiML生成
下記のように、簡単なTwiMLを出力するため、呼び出しをチェインできるようになりました:
<?php require_once './vendor/autoload.php'; use Twilio\TwiML\VoiceResponse; $response = new VoiceResponse(); $response->say('Hello!'); $response->hangup(); echo $response;
Response
インスタンスのメソッドとして、音声通話関連の動詞が用意されています。 また、キーワード引数を使用してこれらの動詞に対して任意の属性を設定できます。 これらすべてはアンダースコア記法を使用します。
このように動詞を入れ子にできることに気づかれるでしょう:
同様の変更はMessage Responseにも当てはまります:
入れ子にされた例です:
REST APIドキュメントでは必須パラメータや各APIオペレーションのサンプルコードを載せています。
例外
Twilio クライアント
In version 4.x, client authentication issues were handled with the generic Services_Twilio_RestException
and only after you try to make a call to a Twilio API.
<?php require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library $sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $token = "your_auth_token"; $client = new Services_Twilio($sid, $token); try { call = $client->account->calls ->get("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); echo $call->to; } catch (Services_Twilio_RestException $e){ echo $e.get_code(); }
In version 5.x you see that authentication exceptions can be handled when initializing the client and catching the ConfigurationException
.
<?php require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library use Twilio\Exceptions\ConfigurationException; use Twilio\Rest\Client; $sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $token = "your_auth_token"; try { $client = new Client($sid, $token); } catch (ConfigurationException $e){ echo $e.get_code(); } call = $client->account->calls ->get("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); echo $call->to;
CurlClient
When initializing the curl client you will see the EnvironmentException
if curl
is not installed on your system.
<?php require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library use Twilio\Exceptions\TwilioException; use Twilio\Http\CurlClient; $sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $token = "your_auth_token"; $client = new Client($sid, $token); try { $client = new CurlClient(); $client->options( 'GET', 'http://api.twilio.com', array(), array(), array(), $sid, $token ); } catch (EnvironmentException $e){ echo $e.get_code(); } echo $call->to;
TwilioException
TwilioException
can be used to handle API errors as shown below. It replaces Services_Twilio_RestException
from version 4.x.
<?php require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library use Twilio\Exceptions\TwilioException; use Twilio\Rest\Client; $sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; $token = "your_auth_token"; $client = new Client($sid, $token); try { call = $client->account->calls ->get("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } catch (TwilioException $e){ echo $e->getStatusCode(); } echo $call->to;
TwimlException
When building TwiML, if it does not conform to what the API expects, you will see TwimlException
instead of Services_Twilio_TwimlException
and can be handled as follows:
<?php require_once './vendor/autoload.php'; use Twilio\Twiml; try { $response = new Twiml(); $dial = $response->dial(); $dial->conference('Room 1234'); echo $response; } catch (TwimlException $e) { echo $e }
APIリクエストのデバッグ
デバッグを容易にするため、ライブラリーでは内部的に使用される、全ヘッダーを含むリクエストおよびレスポンスのオブジェクトへのアクセスが行えるようになっています。 この機能はライブラリーに内蔵されている既定のHTTPクライアントに内蔵されています。
たとえば遅延の原因の追跡を試みる場合、カスタムTwilioヘッダーTwilio-Request-Duration
を取得して、リクエストのTwilioのプラットフォームでの処理にどのくらいの秒数がかかったかを調べることができます。
<?php require_once '/path/to/vendor/autoload.php'; use Twilio\Rest\Client; $sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $token = 'your_auth_token'; $client = new Client($sid, $token); $message = $client->messages->create("+14158675309", array( 'From' => "+14258675310", 'Body' => 'Ahoy!' )); // Retrieve the last response from the HTTP client and inspect the Twilio-Request-Duration header echo($client->getHttpClient()->lastResponse->getHeaders()["Twilio-Request-Duration"]);
お問い合わせ
We'd love to hear your feedback on the PHP SDK, and help you past any issues you may encounter. Feel free to drop us a line, and we'll make sure to get you sorted!
ヘルプが必要ですか?
誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。