15.

PHP Google_Service_Youtube クラス not found エラーの原因と対処

編集
この記事の要点
  • 原因 1: google/apiclient パッケージ未インストール → composer require google/apiclient:^2.0
  • 原因 2: require "vendor/autoload.php" 抜け → autoload を必ず読込
  • 原因 3: composer dump-autoload 忘れ
  • 原因 4: クライアントライブラリ v2 系で名前空間が変わったGoogle_Service_YouTubeGoogle\Service\YouTube
  • 原因 5: GCP コンソールで YouTube Data API v3 が未有効化

エラーメッセージ

PHP Fatal error: Uncaught Error: Class 'Google_Service_Youtube' not found
  in /var/www/app.php:5
Stack trace:
#0 {main}
  thrown in /var/www/app.php on line 5

Google_Service_Youtube (または Google_Service_YouTube 等)は、Google API Client Library for PHP に含まれるYouTube Data API v3 用クラスです。「クラスが見つからない」のは、ほぼautoload / インストール / 名前空間のいずれかの問題です。

原因と対処の早見表

原因確認対処
パッケージ未インストールcomposer show google/apiclientcomposer require google/apiclient:^2.0
vendor/autoload.php 未読込エントリポイントを確認require "vendor/autoload.php" 追加
autoload キャッシュ古いvendor/composer/autoload_*.phpcomposer dump-autoload -o
v2.x の名前空間ミスクライアントライブラリ版数Google\Service\YouTube に変更
YouTube API 無効GCP コンソールで確認API ライブラリで有効化
service クラスのみ別パッケージv2.10.0+ で分離google/apiclient-services も必要

対処1: インストール

# パッケージ確認
composer show | grep google
# google/apiclient            v2.15.0
# google/apiclient-services   v0.331.0
# google/auth                 v1.39.0

# 未インストールの場合
composer require google/apiclient:^2.15.0

# Laravel 12 / PHP 8.2+ の場合は最新版
composer require google/apiclient

対処2: autoload を読み込む

<?php
// ★ 必ずスクリプト先頭で読み込む
require_once __DIR__ . '/vendor/autoload.php';

// Laravel / Symfony なら自動で読まれているので不要

// 直接書く PHP スクリプト・CLI ツールでは必須
$client = new Google\Client();
$client->setDeveloperKey('YOUR_API_KEY');

$youtube = new Google\Service\YouTube($client);

対処3: autoload キャッシュ再生成

# autoload マップを再生成
composer dump-autoload

# 本番では -o で classmap 最適化
composer dump-autoload -o

# プロダクション準拠
composer install --optimize-autoloader --no-dev

対処4: 名前空間の変更(v2.x の重要な変更)

Google API Client Library v2.7.0 以降、クラス名がアンダースコア区切りからモダンな名前空間へ移行しました。古い記事の通り書くと動きません:

// ❌ 旧式(v2.7.0 未満)
$client = new Google_Client();
$client->setDeveloperKey('YOUR_API_KEY');
$youtube = new Google_Service_YouTube($client);

$response = $youtube->search->listSearch('snippet', [
    'q' => 'PHP tutorial',
    'maxResults' => 10,
]);

// ✅ 新式(v2.7.0+, v2.x 推奨)
$client = new Google\Client();
$client->setDeveloperKey('YOUR_API_KEY');
$youtube = new Google\Service\YouTube($client);

$response = $youtube->search->listSearch('snippet', [
    'q' => 'PHP tutorial',
    'maxResults' => 10,
]);

// ※ 旧クラス名はエイリアスとして残存(廃止予定)
// → 警告は出ないが将来的に削除される可能性あり
旧クラス名新クラス名
Google_ClientGoogle\Client
Google_Service_YouTubeGoogle\Service\YouTube
Google_Service_YouTube_SearchListResponseGoogle\Service\YouTube\SearchListResponse
Google_Service_DriveGoogle\Service\Drive
Google_Service_SheetsGoogle\Service\Sheets
Google_Auth_OAuth2Google\Auth\OAuth2

対処5: GCP コンソールで API 有効化

クラスは読み込めても API が無効だと 403 PERMISSION_DENIED が返ります:

  1. GCP コンソールにログイン
  2. プロジェクトを選択(または新規作成)
  3. 「APIとサービス」→「ライブラリ」
  4. 「YouTube Data API v3」を検索
  5. 「有効にする」をクリック
  6. 「認証情報」から API キー or OAuth2 クライアント ID を作成

対処6: services パッケージが別建てになっている

v2.10.0 以降、サービス定義クラスは google/apiclient-services という別パッケージに分離されました。通常は自動依存で入りますが、念のため確認:

composer show google/apiclient-services
# v0.331.0

# 不足していたら個別インストール
composer require google/apiclient-services

完全動作するサンプル

<?php
require __DIR__ . '/vendor/autoload.php';

// 1. クライアント作成
$client = new Google\Client();
$client->setApplicationName('My YouTube Search App');
$client->setDeveloperKey('YOUR_API_KEY');   // GCP コンソールで発行

// 2. YouTube サービス
$youtube = new Google\Service\YouTube($client);

// 3. 動画検索
try {
    $searchResponse = $youtube->search->listSearch('snippet', [
        'q' => 'Laravel tutorial',
        'maxResults' => 5,
        'type' => 'video',
    ]);

    foreach ($searchResponse->items as $item) {
        echo $item->id->videoId . " : " . $item->snippet->title . "\n";
    }
} catch (Google\Service\Exception $e) {
    error_log('API error: ' . $e->getMessage());
} catch (Google\Exception $e) {
    error_log('Client error: ' . $e->getMessage());
}

Laravel での組み込み

// composer require google/apiclient
// .env に YOUTUBE_API_KEY=xxx

// config/services.php
'youtube' => [
    'key' => env('YOUTUBE_API_KEY'),
],

// Service クラス
namespace App\Services;

class YouTubeService
{
    private \Google\Service\YouTube $youtube;

    public function __construct()
    {
        $client = new \Google\Client();
        $client->setDeveloperKey(config('services.youtube.key'));
        $this->youtube = new \Google\Service\YouTube($client);
    }

    public function search(string $query, int $maxResults = 10): array
    {
        $res = $this->youtube->search->listSearch('snippet', [
            'q' => $query,
            'maxResults' => $maxResults,
            'type' => 'video',
        ]);
        return $res->items;
    }
}

// Controller
class VideoController extends Controller
{
    public function index(YouTubeService $yt)
    {
        $items = $yt->search('Laravel 11');
        return view('videos.index', compact('items'));
    }
}

類似エラー

エラー対処
Class 'Google\Client' not found同根。autoload + 名前空間確認
Class 'Google_Service_Drive' not found同根。Drive も同じパッケージ
Class 'Google_Service_Sheets' not found同根
Class 'Google_Auth_AssertionCredentials' not foundv2 で削除済。サービスアカウントは setAuthConfig() + JSON ファイル
quotaExceededYouTube API のクォータ消費上限。GCP コンソールで増加申請
403 The request cannot be completed because you have exceeded your quotaクォータ枯渇

FAQ

Q: 旧 v1 系 (Google API Client v1) を使っている
A: v1 は 2018 年に EOL。v2 へ移行してください。composer require google/apiclient:^2.0

Q: composer.json に書いてあるのにクラスが見つからない
A: composer install または composer update が走っていません。さらに composer dump-autoload

Q: PHP のバージョンが古い
A: 最新の google/apiclient は PHP 8.0+ が必要。古い PHP では古い版数を指定: composer require google/apiclient:^2.12.6

Q: API キーで動かない、OAuth が必要?
A: 検索などの公開データのみなら API キーで OK。ユーザーのチャンネル操作 / アップロードは OAuth2 必須。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. Fatal error: Maximum execution time of 30 seconds exceeded in...
  2. Fatal error: Uncaught Error: Cannot use object of type stdClass as array in ...
  3. Warning: Use of undefined constant ... - assumed '...' (this will throw an Error)
  4. ERROR: Call to undefined method Maatwebsite\Excel\Excel::load()
  5. Maximum execution time of 30 seconds exceeded
  6. Your requirements could not be resolved to an installable set of packages. ... To enable extensions, verify that they are enabled in your .ini files:
  7. could not find driver
  8. the requested PHP extension mbstring is missing from your system.
  9. the requested PHP extension dom is missing from your system.
  10. A non well formed numeric value encountered
  11. Warning: Cannot modify header information - headers already sent by ...
  12. php_network_getaddresses: getaddrinfo failed: Name or service not known
  13. XMLWriter::openUri(): Unable to resolve file path
  14. Object of class stdClass could not be converted to string
  15. Class 'Google_Service_Youtube' not found

最近更新/作成されたページ