PHP で HTTP Cloud Functions の関数を作成してデプロイする

PHP で HTTP Cloud Functions の関数を作成してデプロイする

このガイドでは、PHP ランタイムを使用して Cloud Functions の関数を記述するプロセスを説明します。Cloud Functions の関数には次の 2 つのタイプがあります。

  • HTTP 関数。標準的な HTTP リクエストから呼び出します。
  • イベント ドリブン関数。Pub/Sub トピックのメッセージや Cloud Storage バケットの変更など、Cloud インフラストラクチャのイベントを処理するために使用します。

詳しくは、HTTP 関数の作成イベント ドリブン関数の作成をご覧ください。

始める前に

  1. Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging API を有効にします。

    API を有効にする

  8. gcloud CLI をインストールして初期化します
  9. 次のコマンドを使用して、gcloud コンポーネントを更新してインストールします。
    gcloud components update
  10. 開発環境を準備します。

    Google Cloud での PHP の使用に移動

関数を作成する

  1. 関数コードで使用するため、ローカル システムにディレクトリを作成します。

    Linux / Mac OS X

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    

    Windows

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
  2. helloworld_http ディレクトリに、次の内容の index.php ファイルを作成します。

    <?php
    
    use Google\CloudFunctions\FunctionsFramework;
    use Psr\Http\Message\ServerRequestInterface;
    
    // Register the function with Functions Framework.
    // This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=http` environment
    // variable when deploying. The `FUNCTION_TARGET` environment variable should
    // match the first parameter.
    FunctionsFramework::http('helloHttp', 'helloHttp');
    
    function helloHttp(ServerRequestInterface $request): string
    {
        $name = 'World';
        $body = $request->getBody()->getContents();
        if (!empty($body)) {
            $json = json_decode($body, true);
            if (json_last_error() != JSON_ERROR_NONE) {
                throw new RuntimeException(sprintf(
                    'Could not parse body: %s',
                    json_last_error_msg()
                ));
            }
            $name = $json['name'] ?? $name;
        }
        $queryString = $request->getQueryParams();
        $name = $queryString['name'] ?? $name;
    
        return sprintf('Hello, %s!', htmlspecialchars($name));
    }
    

    このサンプル関数は HTTP リクエストで指定された名前を使用します。名前が指定されていない場合は、「Hello World!」という挨拶を返します。PHP HTTP 関数の構造と必要な要素の詳細については、HTTP 関数を作成するをご覧ください。

依存関係を指定する

  1. PHP では、Composer を使用して依存関係を管理します。Cloud Shell を使用している場合、Composer がプリインストールされています。それ以外の場合は、次のコマンドを使用してインストールできます。

    1. Composer のダウンロード ページにある PHP コマンドライン インストール スクリプトを実行して、Composer を開発マシンにダウンロードします。

    2. composer.phar ファイルを /usr/local/bin ディレクトリに移動します。

      sudo mv composer.phar /usr/local/bin/composer
      
  2. 関数の依存関係を指定します。

    1. 次の内容の composer.json ファイルを helloworld_http ディレクトリに追加します。

      {
          "require": {
              "php": ">= 7.4",
              "google/cloud-functions-framework": "^1.1"
          },
          "scripts": {
              "start": [
                 "Composer\\Config::disableProcessTimeout",
                 "FUNCTION_TARGET=helloHttp php -S localhost:${PORT:-8080} vendor/google/cloud-functions-framework/router.php"
              ]
          }
      }
      

    FUNCTION_TARGET 行は、関数のエントリ ポイントを指定します。

    1. helloworld_http ディレクトリで次のコマンドを実行します。
    composer require google/cloud-functions-framework
    

    これにより、Functions Framework が composer.json に追加され、helloworld_http 内に依存関係を含む vendor ディレクトリが作成されます。

ローカルで関数をビルドしてテストする

関数をデプロイする前にローカルでビルドしてテストするには、次の手順を実施します。

  1. helloHttp 関数を実行するローカル ウェブサーバーを作成します。

    export FUNCTION_TARGET=helloHttp
    composer start
    
  2. ブラウザで http://localhost:8080 にアクセスするか、別のウィンドウから curl localhost:8080 を実行して、関数をテストします。

    詳細については、ローカル関数にリクエストを送信するをご覧ください。

このサンプル関数は、「Hello World!」という挨拶メッセージを返します。

関数をデプロイする

関数をデプロイするには、helloworld_http ディレクトリで次のコマンドを実行します。

  gcloud functions deploy php-http-function \
    --gen2 \
    --runtime=php82 \
    --region=REGION \
    --source=. \
    --entry-point=helloHttp \
    --trigger-http \
    --allow-unauthenticated

REGION は、関数をデプロイする Google Cloud リージョンの名前に置き換えます(us-west1 など)。

オプションの --allow-unauthenticated フラグを使用すると、認証なしで関数にアクセスできます。

デプロイした関数をテストする

  1. 関数がデプロイされたら、gcloud functions deploy コマンドの出力で uri プロパティをメモするか、次のコマンドを使用して取得します。

      gcloud functions describe php-http-function \
        --region=REGION
    

    REGION は、関数をデプロイした Google Cloud リージョンの名前に置き換えます(us-west1 など)。

  2. ブラウザで、この URL にアクセスします。関数から「Hello World!」というメッセージが返されます。

    この URL は Google Cloud コンソールでも確認できます。Cloud Functions の概要ページに移動し、関数の名前をクリックして [関数の詳細] ページを開きます。[トリガー] タブを開き、関数の URL を確認します。

関数のログを表示する

コマンドライン ツールを使用してログを表示する

関数のログは、Cloud Logging UI または Google Cloud CLI で確認できます。

gcloud CLI を使用して関数のログを表示するには、logs read コマンドを使用します。

    gcloud functions logs read \
      --gen2 \
      --limit=10 \
      --region=REGION \
      php-http-function

REGION は、関数をデプロイした Google Cloud リージョンの名前に置き換えます(us-west1 など)。

出力は次のようになります。

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:36.067
LOG:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:22.814
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "hello_http-1" on port 8080.

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:22.777
LOG: [pid1-nginx] Starting nginx (pid 17): /usr/sbin/nginx -c /tmp/nginxconf-953701689/nginx.conf [session:R8F8ZJ5]

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-06-02 19:01:22.766
LOG: [pid1-nginx] Successfully connected to /tmp/google-config/app.sock after 556.430499ms [session:R8F8ZJ5]

ロギング ダッシュボードでログを表示する

ロギング ダッシュボードで関数のログを表示するには、Cloud Functions の概要ページを開き、リストから関数の名前をクリックして、[ログ] タブをクリックします。