טיפול בסשנים באמצעות Firestore

במדריך הזה מוסבר איך לנהל סשנים ב-App Engine.

באפליקציות רבות נדרש ניהול סשנים לצורך אימות והעדפות משתמש. ‫PHP מגיעה עם הטמעה מבוססת-זיכרון לביצוע הפונקציה הזו. עם זאת, ההטמעה הזו לא מתאימה לאפליקציה שאפשר להציג מכמה מופעים, כי הסשן שמתועד במופע אחד עשוי להיות שונה ממופעים אחרים.

מטרות

  • כותבים את האפליקציה.
  • מריצים את האפליקציה באופן מקומי.
  • פורסים את האפליקציה ב-App Engine.

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Google Cloud, והשימוש בהם כרוך בתשלום:

כדי ליצור הערכת עלויות בהתאם לשימוש החזוי, אתם יכולים להשתמש במחשבון התמחור.

משתמשים חדשים של Google Cloud ? יכול להיות שאתם זכאים לתקופת ניסיון בחינם.

כשמסיימים את המשימות שמתוארות במסמך הזה אפשר למחוק את המשאבים שיצרתם כדי להימנע מחיובים נוספים. מידע נוסף זמין בקטע הסרת המשאבים.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אנחנו ממליצים למשתמשים חדשים ב- Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Firestore API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Firestore API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. מגדירים שה-CLI של gcloud ישתמש בפרויקט החדש Google Cloud :
    # Configure gcloud for your project
    gcloud config set project PROJECT_ID
    מחליפים את PROJECT_ID במזהה Google Cloud הפרויקט שיצרתם או שבחרתם קודם.

הגדרת הפרויקט

  1. בחלון הטרמינל, מתחילים בספרייה לפי בחירתכם ויוצרים ספרייה חדשה בשם sessions. כל הקוד של המדריך הזה נמצא בספרייה sessions.

  2. עוברים לספרייה sessions:

    cd sessions
    
  3. מתקינים את יחסי התלות:

    composer require google/cloud-firestore
    

בסוף המדריך הזה, מבנה הקובץ הסופי יהיה דומה לזה:

sessions
├── app.yaml
└── composer.json
├── index.php

כתיבת האפליקציה

  • בחלון הטרמינל, יוצרים קובץ בשם index.php עם התוכן הבא:

    <?php
    /*
     * Copyright 2019 Google LLC
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    use Google\Cloud\Firestore\FirestoreClient;
    
    $projectId = getenv('GOOGLE_CLOUD_PROJECT');
    // Instantiate the Firestore Client for your project ID.
    $firestore = new FirestoreClient([
        'projectId' => $projectId,
    ]);
    
    $handler = $firestore->sessionHandler(['gcLimit' => 500]);
    
    // Configure PHP to use the the Firebase session handler.
    session_set_save_handler($handler, true);
    session_save_path('sessions');
    session_start();
    
    $colors = ['red', 'blue', 'green', 'yellow', 'pink'];
    /**
     * This is an example of a front controller for a flat file PHP site. Using a
     * Static list provides security against URL injection by default.
     */
    switch (@parse_url($_SERVER['REQUEST_URI'])['path']) {
        case '/':
            if (!isset($_SESSION['views'])) {
                $_SESSION['views'] = 0;
                $_SESSION['color'] = $colors[rand(0, 4)];
            }
            printf(
                '<body bgcolor="%s">Views: %s</body>',
                $_SESSION['color'],
                $_SESSION['views']++
            );
            break;
        default:
            http_response_code(404);
            exit('Not Found');
    }
    

האפליקציה הזו מציגה ברכות בשפות שונות לכל משתמש. משתמשים חוזרים תמיד מקבלים את פניית המערכת באותה שפה.

כמה חלונות של אפליקציות שמוצגת בהם ברכה בשפות שונות.

כדי שהאפליקציה תוכל לאחסן העדפות של משתמש, צריך לאחסן מידע על המשתמש הנוכחי בסשן. אפליקציית הדוגמה הזו משתמשת ב-Firestore כדי לאחסן נתוני סשנים.

אפשר להשתמש ב-Firestore session handler כדי להשתמש ב-Firestore עבור סשנים של PHP.

הדיאגרמה הבאה ממחישה איך Firestore מטפל בסשנים באפליקציית App Engine.

תרשים של הארכיטקטורה: משתמש, App Engine, ‏Firestore.

אחרי שמגדירים את session_set_save_handler, לכל בקשה יש משתנה גלובלי $_SESSION שאפשר להשתמש בו כדי לגשת לסשן. נתוני הסשן מאוחסנים ב-Firestore.

הרצה באופן מקומי

  1. מפעילים את שרת האינטרנט המובנה של PHP:

    php -S localhost:8080
    
  2. צפייה באפליקציה בדפדפן האינטרנט:

    Cloud Shell

    בסרגל הכלים של Cloud Shell, לוחצים על Web preview (תצוגה מקדימה של אתר) תצוגה מקדימה של האתר ובוחרים באפשרות Preview on port 8080 (תצוגה מקדימה ביציאה 8080).

    מכונה מקומית

    בדפדפן, עוברים אל http://localhost:8080

    מופיעה אחת מחמש ברכות: "Hello World",‏ "Hallo Welt",‏ "Hola mundo",‏ "Salut le Monde" או "Ciao Mondo". השפה משתנה אם פותחים את הדף בדפדפן אחר או במצב פרטי. אפשר לראות ולערוך את נתוני הסשן Google Cloud במסוף.

    פעילויות ב-Firestore במסוף Google Cloud .

  3. כדי לעצור את שרת ה-HTTP, בחלון הטרמינל, לוחצים על Control+C.

פריסה והפעלה ב-App Engine

אתם יכולים להשתמש בסביבת ברירת המחדל ב-App Engine כדי לפתח ולפרוס אפליקציה שפועלת בצורה מהימנה בעומס כבד ועם כמויות גדולות של נתונים.

במדריך הזה משתמשים בסביבת ברירת המחדל ב-App Engine כדי לפרוס את השרת.

  1. בחלון הטרמינל, יוצרים קובץ app.yaml ומעתיקים את הטקסט הבא:

    runtime: php73
    
  2. פורסים את האפליקציה ב-App Engine:

    gcloud app deploy
    
  3. כדי לראות את האפליקציה הפעילה, מזינים את כתובת ה-URL הבאה:

    https://PROJECT_ID.REGION_ID.r.appspot.com

    מחליפים את מה שכתוב בשדות הבאים:

הברכה נשלחת עכשיו על ידי שרת אינטרנט שפועל במכונה של App Engine.

מחיקת סשנים

PHP מבצע איסוף (GC) של סשנים, שמסיר סשנים ישנים שפג תוקפם בהתאם להגדרות של php.ini. כברירת מחדל, ה-session handler של Firestore לא מנקה סשנים, אבל אפשר להגדיר אותו לעשות את זה על ידי העברת האפשרות gcLimit כשיוצרים את ה-session handler:

$handler = $firestore->sessionHandler(['gcLimit' => 500]);

הסשנים מוסרים באמצעות איסוף אשפה (GC) של סשנים שמבוסס על הסתברות, או כשקוראים לפונקציה session_gc באופן מפורש.

ניפוי באגים באפליקציה

אם אתם לא מצליחים להתחבר לאפליקציית App Engine, כדאי לבדוק את הדברים הבאים:

  1. בודקים שהפקודות gcloud deploy הושלמו בהצלחה ולא הוחזרו שגיאות. אם היו שגיאות (לדוגמה, message=Build failed), תקנו אותן ונסו לפרוס את אפליקציית App Engine שוב.
  2. נכנסים לדף Logs Explorer במסוף Google Cloud .

    כניסה לדף Logs Explorer

    1. ברשימה הנפתחת Recently selected resources, לוחצים על App Engine Application ואז על All module_id. תופיע רשימה של בקשות מהביקור באפליקציה. אם לא מופיעה רשימה של בקשות, ודאו שבחרתם באפשרות All module_id מהרשימה הנפתחת. אם הודעות השגיאה מודפסות ב Google Cloud מסוף, צריך לוודא שהקוד של האפליקציה זהה לקוד שבקטע על כתיבת אפליקציית האינטרנט.

    2. מוודאים ש-Firestore API מופעל.

הסרת המשאבים

מחיקת הפרויקט

  1. במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

מחיקת המכונה של App Engine

  1. במסוף Google Cloud , נכנסים לדף Versions של App Engine.

    כניסה לדף Versions

  2. מסמנים את התיבה שלצד גרסת האפליקציה שלא מוגדרת כברירת מחדל ושרוצים למחוק.
  3. כדי למחוק את גרסת האפליקציה, לוחצים על Delete.

המאמרים הבאים