使用 PHP 创建和部署 HTTP Cloud Functions 函数

使用 PHP 创建和部署 HTTP Cloud Functions 函数

本指南将引导您完成用 PHP 运行时编写 Cloud Functions 函数的过程。Cloud Functions 函数有两种类型:

  • HTTP 函数,通过标准 HTTP 请求调用。
  • 事件驱动型函数,用于处理来自云基础设施的事件,例如 Pub/Sub 主题中收到消息或 Cloud Storage 存储桶发生更改。

如需了解详情,请参阅编写 HTTP 函数编写事件驱动型函数

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Cloud Functions、Cloud Build、Artifact Registry、Cloud Run 和 Cloud Logging API。

    启用 API

  5. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Cloud Functions、Cloud Build、Artifact Registry、Cloud Run 和 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
    

    系统随即会将 Cloud Functions 框架添加到您的 composer.json,并在 helloworld_http 内创建一个包含依赖项的 vendor 目录。

在本地构建和测试函数

如需在部署函数之前在本地构建和测试函数,请执行以下步骤:

  1. 创建一个运行您的 helloHttp 函数的本地 Web 服务器:

    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. 在浏览器中访问此网址。该函数将返回一条“Hello World!”消息。

    您还可以在 Google Cloud 控制台中找到此网址。转到 Cloud Functions 概览页面,点击函数的名称以打开其函数详情页面。打开触发器标签页以查看函数的网址。

查看函数日志

使用命令行工具查看日志

您可以使用 Cloud Logging 界面或通过 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 概览页面,点击列表中的函数名称,然后点击日志标签页。