Crea ed esegui il deployment di una funzione Cloud Run HTTP con PHP

Questa guida illustra la procedura per scrivere una funzione Cloud Run utilizzando il runtime PHP, quindi per testare ed eseguire il deployment della funzione HTTP.

Puoi creare due tipi di funzioni Cloud Run:

  • Una funzione HTTP, che richiami dalle richieste HTTP standard.
  • Una funzione basata su eventi che utilizzi per gestire gli eventi della tua infrastruttura Cloud, ad esempio i messaggi in un argomento Pub/Sub o le modifiche in un bucket Cloud Storage.

Per maggiori dettagli, consulta Scrittura di funzioni HTTP e la scrittura di funzioni basate su eventi.

Prima di iniziare

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  8. Installa e inizializza gcloud CLI.
  9. Aggiorna e installa i componenti di gcloud con quanto segue .
    gcloud components update
  10. Prepara l'ambiente di sviluppo.

    Vai a Utilizzo di PHP su Google Cloud

Crea la funzione

  1. Crea una directory sul tuo sistema locale per il codice della funzione:

    Linux o Mac OS X

    mkdir ~/helloworld_http
    cd ~/helloworld_http
    

    Windows

    mkdir %HOMEPATH%\helloworld_http
    cd %HOMEPATH%\helloworld_http
    
  2. Crea un file index.php nella directory helloworld_http con seguenti contenuti:

    <?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));
    }
    

    Questa funzione di esempio prende un nome fornito nella richiesta HTTP e restituisce un saluto oppure "Hello World!" se non viene fornito alcun nome. Per ulteriori informazioni sulla struttura e sugli elementi obbligatori di una funzione HTTP PHP, consulta Scrivere funzioni HTTP.

Specifica delle dipendenze

  1. PHP usa Composer per gestire le dipendenze. Se utilizzi Cloud Shell, Composer è preinstallato. In caso contrario, segui le istruzioni di installazione di Composer.

  2. Specifica le dipendenze della funzione:

    1. Aggiungi un file composer.json con i seguenti contenuti a nella directory helloworld_http:

      {
          "require": {
              "php": ">= 8.1",
              "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"
              ]
          }
      }
      

    La riga FUNCTION_TARGET specifica l'entry point della funzione.

    1. Esegui questo comando nella directory helloworld_http:
    composer require google/cloud-functions-framework
    

    Questo aggiunge il framework di Functions a composer.json e crea un directory vendor all'interno di helloworld_http che contiene la delle dipendenze.

Crea e testa la tua funzione in locale

Per creare e testare la tua funzione localmente prima di eseguirne il deployment, esegui la seguenti passaggi:

  1. Crea un server web locale che esegue la funzione helloHttp:

    export FUNCTION_TARGET=helloHttp
    composer start
    
  2. Testa la funzione visitando http://localhost:8080 in un browser oppure eseguendo curl localhost:8080 da un'altra finestra.

    Per maggiori dettagli, consulta Inviare richieste alle funzioni locali.

Questa funzione di esempio restituisce un allegro messaggio "Hello, World!".

esegui il deployment della funzione

Per il deployment della funzione, esegui questo comando nella directory helloworld_http:

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

Sostituisci REGION con il nome della regione Google Cloud in cui vuoi eseguire il deployment della funzione (ad es. us-west1).

Il flag facoltativo --allow-unauthenticated ti consente di raggiungere la funzione senza autenticazione.

Testa la funzione di cui hai eseguito il deployment

  1. Dopo il deployment della funzione, prendi nota della proprietà uri dall'output del comando gcloud functions deploy o recuperala con il seguente comando:

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

    Sostituisci REGION con il nome della regione Google Cloud in cui hai eseguito il deployment della funzione (ad es. us-west1).

  2. Accedi all'URL dal browser. La funzione restituisce un messaggio "Hello World!" per creare un nuovo messaggio email.

    Puoi trovare questo URL anche nella console Google Cloud. Vai alla pagina Panoramica delle funzioni Cloud Run e fai clic sul nome della funzione per aprire la pagina Dettagli funzione. Apri la scheda ATTIVAZIONE per visualizzare l'URL della funzione.

Visualizza i log della funzione

Visualizza i log con lo strumento a riga di comando

Puoi rivedere i log della funzione con l'interfaccia utente di Cloud Logging o tramite Google Cloud CLI.

Per visualizzare i log per la tua funzione con gcloud CLI, utilizza il metodo Comando logs read:

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

Sostituisci REGION con il nome della regione Google Cloud in cui hai eseguito il deployment della funzione (ad es. us-west1).

L'output è simile al seguente:

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]

Visualizzare i log con la dashboard di logging

Per visualizzare i log per la funzione con la dashboard di logging, apri la Pagina Panoramica delle funzioni di Cloud Run e fai clic su il nome della funzione nell'elenco, poi fai clic sulla scheda Log.