Twitch API v5 を利用して人気のゲーム情報を取得する

Twitch API v5を利用して人気のゲーム情報を取得することができる。New Twitch APIでも可能だが、取得できるのは、現在の視聴数順にソートされたゲーム情報だけになる。v5はすでにdeprecatedなAPIとしてアナウンスされているが、ゲーム情報に加え、視聴数や配信チャンネル数も取得することができるため、New Twitch APIよりも利用価値が高い。

下記は、v5を利用して人気のゲーム情報を取得するコードの例。


class TwitchApi_v5_Client
{
  private $endpoint = 'https://api.twitch.tv/kraken/';

  private $oauthClientIdHeader;

  public function __construct($CLIENT_ID, $ACCESS_TOKEN = "")
  {
    $this->oauthClientIdHeader = "Client-ID: $CLIENT_ID";
  }

  public function get($resource, array $queryParams)
  {
    $url = $this->endpoint . $resource;

    if (!empty($queryParams))
      $url .= '?' . http_build_query($queryParams);

    $response = $this->execCurlGET($url);
    sleep(1);

    return json_decode($response, true);
  }

  private function execCurlGET($url)
  {
    $cmd = 'curl' .
           " -H 'Accept: application/vnd.twitchtv.v5+json'" .
           " -H '{$this->oauthClientIdHeader}'" .
           " -X GET '$url'";

    echo "# $cmd\n";

    return exec($cmd);
  }
}


$CLIENT_ID = '_CLIENT_ID_';
$client = new TwitchApi_v5_Client($CLIENT_ID);

$params = [
  //'limit' => 100,
  //'offset' => 0,
];

$response = $client->get('games/top', $params);
var_dump($response);

v5で人気のゲーム情報を取得するには、下記のURLに対してGETリクエストを送信すれば良い。

https://api.twitch.tv/kraken/games/top

リクエスト時のクエリパラメータとして、limit パラメータを指定すると、APIレスポンスに含める結果の件数を変更することができる。デフォルトは 10 で10件のゲーム情報がレスポンスとして返される。最大値は 100 までとなる。

また、offset パラメータを指定することにより、レスポンスデータのページネーションを行うことができる。デフォルトでは、0 が設定され、1ページ目の結果がレスポンスとして返される。2ページ目以降の結果を取得するには、この値をインクリメントしていけば良い。

APIリクエスト実行後、レスポンスデータの top フィールドにゲーム情報(game オブジェクト)が含まれている。viewers プロパティがそのゲームの現在の視聴数、channels プロパティが現在配信しているチャンネル数を表す。現在の視聴数とチャンネル数は、New Twitch APIではレスポンスデータに含まれないため、これらのデータを取得したい場合は、v5を利用する必要がある。

New Twitch API を利用して動画情報を取得する

New Twitch APIを利用してユーザーに紐付いた動画情報やゲームに紐付いた動画情報を取得することができる。

下記はAPIを利用して動画情報を取得するコードの例。


class TwitchApiClient
{
  private $endpoint = 'https://api.twitch.tv/helix/';

  private $oauthClientIdHeader;
  private $oauthTokenHeader;

  public function __construct($CLIENT_ID, $ACCESS_TOKEN)
  {
    $this->oauthClientIdHeader = "Client-ID: $CLIENT_ID";
    $this->oauthTokenHeader = "Authorization: Bearer $ACCESS_TOKEN";
  }

  public function get($resource, array $queryParams)
  {
    $url = $this->endpoint . $resource;

    if (!empty($queryParams))
      $url .= '?' . http_build_query($queryParams);

    $response = $this->execCurlGET($url);
    sleep(1);

    return json_decode($response, true);
  }

  private function execCurlGET($url)
  {
    $cmd = 'curl' .
           " -H '{$this->oauthClientIdHeader}'" .
           " -H '{$this->oauthTokenHeader}'" .
           " -X GET '$url'";

    echo "# $cmd\n";

    return exec($cmd);
  }
}


$CLIENT_ID = '_CLIENT_ID_';
$ACCESS_TOKEN = '_ACCESS_TOKEN_';

$client = new TwitchApiClient($CLIENT_ID, $ACCESS_TOKEN);

$params = [
  //'user_id' => '19571641', // ninja
  'game_id' => '33214', // Fortnite
  'first' => 20,
  'period' => 'all',
  'sort' => 'views',
  'type' => 'all',
];

$page = 0;
do
{
  $response = $client->get('videos', $params);
  var_dump($response);
  $page++;

  if (isset($response['pagination']['cursor']))
    $params['after'] = $response['pagination']['cursor'];
  else
    break;

  if ($page >= 2)
    break;

} while(true);

動画情報を取得するには、下記のURLに対してGETリクエストを行えば良い。

https://api.twitch.tv/helix/videos

GETリクエストを行う際の必須クエリパラメータとして、user_id パラメータにユーザーIDを指定した場合は、そのユーザーに紐付いた動画情報、game_id パラメータにゲームIDを指定した場合は、そのゲームに紐付いた動画情報を取得することができる。上記のコードの例では、game_id にFortniteのゲームIDを指定している。

次に上記のコードで設定しているオプションのクエリパラメータを順に説明していく。

first パラメータに値を設定すると、APIレスポンスに含める動画情報の件数を指定することができる。デフォルト値は 20、最大 100 まで指定することができる。

period パラメータには、いつ作成された動画を取得対象にするか、その期間を指定できる。デフォルト値は all で全ての期間が対象となる。他には、dayweekmonth を指定することができる。

sort パラメータでは、レスポンスに含まれる動画情報リストのソート方法を指定できる。デフォルト値は time で新しい動画順にソートされる。views を指定すると視聴数(再生回数)が多い順にソートされる。他には trending も指定可能であるが、上記のコードを実行して確認した時点では、"503 Service Unavailable" で結果を取得することができなかった。

type パラメータでは、レスポンスに含める動画の種類を指定することができる。デフォルト値は all で全ての動画の種類がレスポンスに含まれる。upload を指定するとアップロード動画、archive を指定するとライブ配信のアーカイブ動画、highlight を指定するとダイジェスト動画に限定した結果を取得することができる。

APIリクエスト実行後、レスポンスデータの data フィールドにクエリパラメータの指定条件にマッチした動画情報リストが含まれている。また、APIリクエスト時に、レスポンスデータの pagination フィールドにある cursor プロパティの値を after パラメータの値に指定してリクエストを行うと、レスポンスデータの次の結果セットを取得することができる。

Twitch API v5 を利用してユーザー情報を取得する

Twitch API v5はすでにdeprecatedであるが、v5でユーザー情報を取得する方法を記載する。あえてv5でユーザー情報を取得する理由は、New Twitch APIで取得できるユーザー情報には、アカウント作成日時や更新日時が含まれていないが、Twitch API v5ではそれが取得可能なため。

下記はv5を利用してユーザー情報を取得するコード。


class TwitchApi_v5_Client
{
  private $endpoint = 'https://api.twitch.tv/kraken/';

  private $oauthClientIdHeader;

  public function __construct($CLIENT_ID, $ACCESS_TOKEN = "")
  {
    $this->oauthClientIdHeader = "Client-ID: $CLIENT_ID";
  }

  public function get($resource, array $queryParams)
  {
    $url = $this->endpoint . $resource;

    if (!empty($queryParams))
      $url .= '?' . http_build_query($queryParams);

    $response = $this->execCurlGET($url);
    sleep(1);

    return json_decode($response, true);
  }

  private function execCurlGET($url)
  {
    $cmd = 'curl' .
           " -H 'Accept: application/vnd.twitchtv.v5+json'" .
           " -H '{$this->oauthClientIdHeader}'" .
           " -X GET '$url'";

    echo "# $cmd\n";

    return exec($cmd);
  }
}


$CLIENT_ID = '_CLIENT_ID_';
$client = new TwitchApi_v5_Client($CLIENT_ID);

$params = [
  'login' => 'ninja',
];

$response = $client->get('users', $params);
var_dump($response);

Twitch API v5でユーザー情報を取得するには、

https://api.twitch.tv/kraken/users

に対し、クエリパラメータとして、login パラメータにユーザー名を指定してGETリクエストを行えば良い。
※公式ドキュメントでは リクエストURLに user IDs と記載されていて紛らわしいが、ユーザーIDではなくユーザー名を指定する。

上記のコードを実行するとAPIレスポンスとして、下記のようなユーザー情報を取得することできる。
※実際はAPIレスポンスとしてJSONデータが返されるが、json_decode() を使って配列データに変換している。

レスポンスデータに含まれる created_atupdated_at がNew Twitch APIでは取得できない情報で、それぞれアカウントの作成日時、更新日時にあたる情報となる。


array(2) {
  ["_total"]=>
  int(1)
  ["users"]=>
  array(1) {
    [0]=>
    array(8) {
      ["display_name"]=>
      string(5) "Ninja"
      ["_id"]=>
      string(8) "19571641"
      ["name"]=>
      string(5) "ninja"
      ["type"]=>
      string(4) "user"
      ["bio"]=>
      NULL
      ["created_at"]=>
      string(27) "2011-01-16T04:31:20.024666Z"
      ["updated_at"]=>
      string(27) "2020-08-26T11:23:23.750014Z"
      ["logo"]=>
      string(109) "https://static-cdn.jtvnw.net/jtv_user_pictures/cef31105-8a6e-4211-a74b-2f0bbd9791fb-profile_image-300x300.png"
    }
  }
}

New Twitch API を利用してユーザー(チャンネル)のフォロワー数を取得する

New Twitch APIを利用してユーザー(チャンネル)のフォロワー数を取得する。Twitch API v5ではフォロワー数はチャンネルオブジェクトのプロパティの一つであったが、New Twitch APIではデータモデルが見直され、チャンネルオブジェクトはユーザーオブジェクトに統合された。よって、New Twitch APIでは、ユーザーリソースに対してリクエストを行うことによって、フォロワー数を取得することができる。

下記は、New Twitch APIでユーザーリソースに対してリクエストを行い、フォロワー数を取得するコードの例。


class TwitchApiClient
{
  private $endpoint = 'https://api.twitch.tv/helix/';

  private $oauthClientIdHeader;
  private $oauthTokenHeader;

  public function __construct($CLIENT_ID, $ACCESS_TOKEN)
  {
    $this->oauthClientIdHeader = "Client-ID: $CLIENT_ID";
    $this->oauthTokenHeader = "Authorization: Bearer $ACCESS_TOKEN";
  }

  public function get($resource, array $queryParams)
  {
    $url = $this->endpoint . $resource;

    if (!empty($queryParams))
      $url .= '?' . http_build_query($queryParams);

    $response = $this->execCurlGET($url);
    sleep(1);

    return json_decode($response, true);
  }

  private function execCurlGET($url)
  {
    $cmd = 'curl' .
           " -H '{$this->oauthClientIdHeader}'" .
           " -H '{$this->oauthTokenHeader}'" .
           " -X GET '$url'";

    echo "# $cmd\n";

    return exec($cmd);
  }
}


$CLIENT_ID = '_CLIENT_ID_';
$ACCESS_TOKEN = '_ACCESS_TOKEN_';

$client = new TwitchApiClient($CLIENT_ID, $ACCESS_TOKEN);

$params = [
  'to_id' => '19571641', // ninja
  'first' => 1,
];

$response = $client->get('users/follows', $params);
var_dump($response);

フォロワー数は、

https://api.twitch.tv/helix/users/follows

に対し、クエリパラメータとして to_id パラメータを付加してGETリクエストを行うことによって取得することができる。

to_id にはユーザーIDを指定する。上記のコードの例では、ユーザー名 ninja のユーザーIDを指定している。

APIレスポンスとして返ってくるデータは、totaldatapagination フィールドから構成され、total の値が取得したいフォロワー数に該当する。

data フィールドには、フォロワーのユーザー情報が含まれている。デフォルトでは20件のユーザー情報が含まれる。この件数は、APIリクエストを行う際のクエリパラメータとして first パラメータに値を設定することで変更できる。設定できる最大値は 100 まで。上記のコードの例では、フォロワー数を取得するのが主な目的なため、first1 を指定し、レスポンスに含めるデータ件数を抑制している。

pagination フィールドのデータは、結果のページネーションに利用するためのもの。data フィールドに含まれるユーザー情報の次の結果セットを取得したい場合、APIリクエスト時のクエリパラメータとして after パラメータに pagination フィールドの cursor の値を指定すれば良い。

Twitch API v5 を利用して人気の動画情報を取得する

Twitch API v5を利用して人気の動画情報を取得することができる。これは特定の期間における視聴数(再生回数)に基づいたもので、視聴数が多い順にソートされた動画情報がAPIレスポンスとして返ってくる。

Twitch API v5はすでにdeprecatedで、New Twitch APIを利用することが推奨されているが、New Twitch APIには現状、人気の動画情報をリクエストする手段が提供されていないので、v5を利用する。

下記は、v5を利用して人気の動画情報を取得するコード。


class TwitchApi_v5_Client
{
  private $endpoint = 'https://api.twitch.tv/kraken/';

  private $oauthClientIdHeader;

  public function __construct($CLIENT_ID, $ACCESS_TOKEN = "")
  {
    $this->oauthClientIdHeader = "Client-ID: $CLIENT_ID";
  }

  public function get($resource, array $queryParams)
  {
    $url = $this->endpoint . $resource;

    if (!empty($queryParams))
      $url .= '?' . http_build_query($queryParams);

    $response = $this->execCurlGET($url);
    sleep(1);

    return json_decode($response, true);
  }

  private function execCurlGET($url)
  {
    $cmd = 'curl' .
           " -H 'Accept: application/vnd.twitchtv.v5+json'" .
           " -H '{$this->oauthClientIdHeader}'" .
           " -X GET '$url'";

    echo "# $cmd\n";

    return exec($cmd);
  }
}


$CLIENT_ID = '_CLIENT_ID_';
$client = new TwitchApi_v5_Client($CLIENT_ID);

$params = [
  'language' => 'en,ja',
  'period' => 'all',
  'limit' => 20,
  'offset' => 0,
];

do
{
  $response = $client->get('videos/top', $params);
  var_dump($response);
  $params['offset']++;

  if ($params['offset'] >= 2)
    break;

} while($response);

Twitch API v5を利用して人気の動画情報を取得するには下記のURLに対してGETリクエストを送信すれば良い。

https://api.twitch.tv/kraken/videos/top

APIリクエストを送る際のクエリパラメータとして、上記のコードの例では、languageperiodlimitoffset パラメータを設定している。

language パラメータに言語コードを指定すると、APIレスポンスに含める結果を指定した言語に紐付いたものに限定させることができる。上記の例では、en,ja を指定し英語と日本語の動画に限定している。

period パラメータでは、人気の期間を指定することができる。この値には、weekmonthall のいずれかを指定できる。上記の例では、all を指定し全期間における累計の視聴数に基づいた結果を取得するようにしている。

limit パラメータは、APIレスポンスに含める動画件数を指定するもので、デフォルト値は 10、最大値として 100 を設定できる。今回の例では、20 を指定し、1回のリクエストあたり20件の結果を取得するようにしている。

offset パラメータは、結果のページネーションのためのもので、デフォルトでは 0 が設定される。このパラメータの値をインクリメントしていけば、次の結果を順に取得していくことができる。

Google APIs Client Library for PHP における YouTube サービスの実装の概要を確認する

YouTube Data API v3において定義されているリソースとPHPクライアントライブラリ (Google APIs Client Library for PHP) における実装がどのように対応しているか見ていきたい。

対応関係の概要だけでも知っておくと、APIリファレンスを読むとき、ドキュメント上での記述とPHPでアプリケーションを実装する際に必要なコードを頭の中で対応付けられるようになる。

APIリファレンスに記載されている通り、APIを利用して操作できるリソースには下記のものがある。

  • activities リソース
  • captions リソース
  • channelBanners リソース
  • channelSections リソース
  • channels リソース
  • commentThreads リソース
  • comments リソース
  • guideCategories リソース
  • i18nLanguages リソース
  • i18nRegions リソース
  • liveBroadcasts リソース(APIレファレンスに記載なし)
  • liveChatBans リソース(APIレファレンスに記載なし)
  • liveChatMessages リソース(APIレファレンスに記載なし)
  • liveChatModerators リソース(APIレファレンスに記載なし)
  • liveStreams リソース(APIレファレンスに記載なし)
  • members リソース
  • membershipsLevels リソース
  • playlistItems リソース
  • playlists リソース
  • search リソース
  • sponsors リソース(APIレファレンスに記載なし)
  • subscriptions リソース
  • superChatEvents リソース(APIレファレンスに記載なし)
  • thumbnails リソース
  • videoAbuseReportReasons リソース
  • videoCategories リソース
  • videos リソース
  • watermarks リソース

これらのリソースとPHPクライアントライブラリにおける実装の対応関係を見ていくために、簡単なコードを使って結果を確認していく。


まず、YouTube Data APIのリクエスト操作を行うには、下記のように Google_Service_YouTube オブジェクトを作成する。


require_once '/path/to/google-api-php-client/vendor/autoload.php';

$client = new Google_Client();
$client->setDeveloperKey("_API_KEY_");
$youtube = new Google_Service_YouTube($client);

ここで下記のコードを実行すると、$youtube (Google_Service_YouTube オブジェクト) が持つプロパティと、そのクラスを確認することができる。


$propertyNames = [
  'activities',
  'captions',
  'channelBanners',
  'channelSections',
  'channels',
  'commentThreads',
  'comments',
  'guideCategories',
  'i18nLanguages',
  'i18nRegions',
  'liveBroadcasts',
  'liveChatBans',
  'liveChatMessages',
  'liveChatModerators',
  'liveStreams',
  'members',
  'membershipsLevels',
  'playlistItems',
  'playlists',
  'search',
  'sponsors',
  'subscriptions',
  'superChatEvents',
  'thumbnails',
  'videoAbuseReportReasons',
  'videoCategories',
  'videos',
  'watermarks',
];

foreach ($propertyNames as $propertyName)
{
  echo "property: ".'$youtube->'."$propertyName\n";

  if (property_exists($youtube, $propertyName))
  {
    echo "  ==> class       : " . get_class($youtube->$propertyName) . "\n";
    echo "  ==> parent class: " . get_parent_class($youtube->$propertyName) . "\n\n";
  }
  else
  {
    echo "  ==> not exists\n\n";
  }
}
[実行結果]

property: $youtube->activities
  ==> class       : Google_Service_YouTube_Resource_Activities
  ==> parent class: Google_Service_Resource

property: $youtube->captions
  ==> class       : Google_Service_YouTube_Resource_Captions
  ==> parent class: Google_Service_Resource

property: $youtube->channelBanners
  ==> class       : Google_Service_YouTube_Resource_ChannelBanners
  ==> parent class: Google_Service_Resource

property: $youtube->channelSections
  ==> class       : Google_Service_YouTube_Resource_ChannelSections
  ==> parent class: Google_Service_Resource

property: $youtube->channels
  ==> class       : Google_Service_YouTube_Resource_Channels
  ==> parent class: Google_Service_Resource

property: $youtube->commentThreads
  ==> class       : Google_Service_YouTube_Resource_CommentThreads
  ==> parent class: Google_Service_Resource

property: $youtube->comments
  ==> class       : Google_Service_YouTube_Resource_Comments
  ==> parent class: Google_Service_Resource

property: $youtube->guideCategories
  ==> class       : Google_Service_YouTube_Resource_GuideCategories
  ==> parent class: Google_Service_Resource

property: $youtube->i18nLanguages
  ==> class       : Google_Service_YouTube_Resource_I18nLanguages
  ==> parent class: Google_Service_Resource

property: $youtube->i18nRegions
  ==> class       : Google_Service_YouTube_Resource_I18nRegions
  ==> parent class: Google_Service_Resource

property: $youtube->liveBroadcasts
  ==> class       : Google_Service_YouTube_Resource_LiveBroadcasts
  ==> parent class: Google_Service_Resource

property: $youtube->liveChatBans
  ==> class       : Google_Service_YouTube_Resource_LiveChatBans
  ==> parent class: Google_Service_Resource

property: $youtube->liveChatMessages
  ==> class       : Google_Service_YouTube_Resource_LiveChatMessages
  ==> parent class: Google_Service_Resource

property: $youtube->liveChatModerators
  ==> class       : Google_Service_YouTube_Resource_LiveChatModerators
  ==> parent class: Google_Service_Resource

property: $youtube->liveStreams
  ==> class       : Google_Service_YouTube_Resource_LiveStreams
  ==> parent class: Google_Service_Resource

property: $youtube->members
  ==> class       : Google_Service_YouTube_Resource_Members
  ==> parent class: Google_Service_Resource

property: $youtube->membershipsLevels
  ==> class       : Google_Service_YouTube_Resource_MembershipsLevels
  ==> parent class: Google_Service_Resource

property: $youtube->playlistItems
  ==> class       : Google_Service_YouTube_Resource_PlaylistItems
  ==> parent class: Google_Service_Resource

property: $youtube->playlists
  ==> class       : Google_Service_YouTube_Resource_Playlists
  ==> parent class: Google_Service_Resource

property: $youtube->search
  ==> class       : Google_Service_YouTube_Resource_Search
  ==> parent class: Google_Service_Resource

property: $youtube->sponsors
  ==> class       : Google_Service_YouTube_Resource_Sponsors
  ==> parent class: Google_Service_Resource

property: $youtube->subscriptions
  ==> class       : Google_Service_YouTube_Resource_Subscriptions
  ==> parent class: Google_Service_Resource

property: $youtube->superChatEvents
  ==> class       : Google_Service_YouTube_Resource_SuperChatEvents
  ==> parent class: Google_Service_Resource

property: $youtube->thumbnails
  ==> class       : Google_Service_YouTube_Resource_Thumbnails
  ==> parent class: Google_Service_Resource

property: $youtube->videoAbuseReportReasons
  ==> class       : Google_Service_YouTube_Resource_VideoAbuseReportReasons
  ==> parent class: Google_Service_Resource

property: $youtube->videoCategories
  ==> class       : Google_Service_YouTube_Resource_VideoCategories
  ==> parent class: Google_Service_Resource

property: $youtube->videos
  ==> class       : Google_Service_YouTube_Resource_Videos
  ==> parent class: Google_Service_Resource

property: $youtube->watermarks
  ==> class       : Google_Service_YouTube_Resource_Watermarks
  ==> parent class: Google_Service_Resource

実行結果を見ると、例えば $youtube オブジェクトは、videos リソースに対応する videos プロパティを持ち、そのプロパティは Google_Service_YouTube_Resource_Videos クラスのオブジェクトであることが分かる。また、各プロパティに対応するクラスは、全て Google_Service_Resource クラスを親に持つことが分かる。

このことから、APIリファレンスに記載された videos リソースに関する説明は、PHPでは $youtube (Google_Service_YouTube オブジェクト) の videos プロパティに関する説明と解釈することができる。


次に、プロパティが持つメソッドを見ていきたい。下記のコードを実行すると、各プロパティが持つメソッドを確認することができる。


$methodNames = [
 'list',
 'insert',
 'update',
 'download',
 'delete',
 'markAsSpam',
 'setModerationStatus',
 'rate',
 'getRating',
 'reportAbuse',
 'set',
 'unset',
];

foreach ($propertyNames as $propertyName)
{
  echo "property: ".'$youtube->'."$propertyName\n";

  foreach ($methodNames as $methodName)
  {
    if (method_exists($youtube->$propertyName, $methodName))
    {
      echo "  ==> {$methodName}()\n";
    }
    else
    {
      $PropertyName = $propertyName;
      $PropertyName[0] = strtoupper($PropertyName[0]);

      $methodNamePropertyName = $methodName . $PropertyName;

      if (method_exists($youtube->$propertyName, $methodNamePropertyName))
      {
        echo "  ==> {$methodNamePropertyName}()\n";
      }
    }
  }
  echo "\n";
}
[実行結果]

property: $youtube->activities
  ==> listActivities()
  ==> insert()

property: $youtube->captions
  ==> listCaptions()
  ==> insert()
  ==> update()
  ==> download()
  ==> delete()

property: $youtube->channelBanners
  ==> insert()

property: $youtube->channelSections
  ==> listChannelSections()
  ==> insert()
  ==> update()
  ==> delete()

property: $youtube->channels
  ==> listChannels()
  ==> update()

property: $youtube->commentThreads
  ==> listCommentThreads()
  ==> insert()
  ==> update()

property: $youtube->comments
  ==> listComments()
  ==> insert()
  ==> update()
  ==> delete()
  ==> markAsSpam()
  ==> setModerationStatus()

property: $youtube->guideCategories
  ==> listGuideCategories()

property: $youtube->i18nLanguages
  ==> listI18nLanguages()

property: $youtube->i18nRegions
  ==> listI18nRegions()

property: $youtube->liveBroadcasts
  ==> listLiveBroadcasts()
  ==> insert()
  ==> update()
  ==> delete()

property: $youtube->liveChatBans
  ==> insert()
  ==> delete()

property: $youtube->liveChatMessages
  ==> listLiveChatMessages()
  ==> insert()
  ==> delete()

property: $youtube->liveChatModerators
  ==> listLiveChatModerators()
  ==> insert()
  ==> delete()

property: $youtube->liveStreams
  ==> listLiveStreams()
  ==> insert()
  ==> update()
  ==> delete()

property: $youtube->members
  ==> listMembers()

property: $youtube->membershipsLevels
  ==> listMembershipsLevels()

property: $youtube->playlistItems
  ==> listPlaylistItems()
  ==> insert()
  ==> update()
  ==> delete()

property: $youtube->playlists
  ==> listPlaylists()
  ==> insert()
  ==> update()
  ==> delete()

property: $youtube->search
  ==> listSearch()

property: $youtube->sponsors
  ==> listSponsors()

property: $youtube->subscriptions
  ==> listSubscriptions()
  ==> insert()
  ==> delete()

property: $youtube->superChatEvents
  ==> listSuperChatEvents()

property: $youtube->thumbnails
  ==> set()

property: $youtube->videoAbuseReportReasons
  ==> listVideoAbuseReportReasons()

property: $youtube->videoCategories
  ==> listVideoCategories()

property: $youtube->videos
  ==> listVideos()
  ==> insert()
  ==> update()
  ==> delete()
  ==> rate()
  ==> getRating()
  ==> reportAbuse()

property: $youtube->watermarks
  ==> set()
  ==> unsetWatermarks()

実行結果を見ると、list メソッド以外は、APIリファレンスに記載された通りの名前でメソッドが用意されている。list メソッドについては、listVideos のようにリソース名が付いた名前となっている。おそらく、これは、list() がPHPにおいて特別な意味を持つキーワードとして登録されているので、混乱を避けるためにこのようなメソッド名を採用したと考えられる。


最後にAPIレスポンスについて見ていきたい。下記のコードを実行するとレスポンスに含まれるプロパティと、そのクラスを確認することができる。


$channelId = "UCrXUsMBcfTVqwAS7DKg9C0Q"; // YouTube Japan

$params = [
  'id' => $channelId
];

$response = $youtube->channels->listChannels('snippet', $params);

echo "response\n";
echo "  ==> class              : " . get_class($response) . "\n";
echo "  ==> parent class       : " . get_parent_class($response) . "\n";
echo "  ==> parent parent class: " . get_parent_class(get_parent_class($response)) . "\n\n";

echo "response.pageInfo\n";
echo "  ==> class       : " . get_class($response['pageInfo']) . "\n";
echo "  ==> parent class: " . get_parent_class($response['pageInfo']) . "\n\n";

echo "// access as array\n";

foreach ($response['items'] as $item)
{
  echo "item\n";
  echo "  ==> class       : " . get_class($item) . "\n";
  echo "  ==> parent class: " . get_parent_class($item) . "\n\n";

  echo "item.snippet\n";
  echo "  ==> class       : " . get_class($item['snippet']) . "\n";
  echo "  ==> parent class: " . get_parent_class($item['snippet']) . "\n\n";
}

echo "// access with arrow operator\n";

foreach ($response->items as $item)
{
  echo "item.snippet\n";
  echo "  ==> class       : " . get_class($item->snippet) . "\n";
  echo "  ==> parent class: " . get_parent_class($item->snippet) . "\n\n";
}

echo "// just iterate over the object\n";

foreach ($response as $item)
{
  echo "item.snippet\n";
  echo "  ==> class       : " . get_class($item['snippet']) . "\n";
  echo "  ==> parent class: " . get_parent_class($item['snippet']) . "\n\n";
}
[実行結果]

response
  ==> class              : Google_Service_YouTube_ChannelListResponse
  ==> parent class       : Google_Collection
  ==> parent parent class: Google_Model

response.pageInfo
  ==> class       : Google_Service_YouTube_PageInfo
  ==> parent class: Google_Model

// access as array
item
  ==> class       : Google_Service_YouTube_Channel
  ==> parent class: Google_Model

item.snippet
  ==> class       : Google_Service_YouTube_ChannelSnippet
  ==> parent class: Google_Model

// access with arrow operator
item.snippet
  ==> class       : Google_Service_YouTube_ChannelSnippet
  ==> parent class: Google_Model

// just iterate over the object
item.snippet
  ==> class       : Google_Service_YouTube_ChannelSnippet
  ==> parent class: Google_Model

実行結果からAPIレスポンスに含まれるプロパティは、全て Google_Model を継承したクラスのオブジェクトであることが分かる。

Google_Model クラスは、ArrayAccess インターフェイスを実装したクラスとなっているため、アロー演算子を使わず配列としてオブジェクトのプロパティにアクセスすることが可能となっている。

Google_Collection クラスは Iterator インターフェイスを実装したクラスで、反復処理では自動的に items 配列を参照するようになっているので、例えば、foreach を使うとき、

foreach ($response['items'] as $item)

と明示的に items 配列を書かなくても、

foreach ($response as $item)

というように、単に $response オブジェクトに対して foreach を書くことができる。