This topic describes how to implement lifecycle hooks for function instances in the PHP runtime environment.

Background information

After you configure a lifecycle hook for a function instance, Function Compute invokes the hook when a related lifecycle event for the instance occurs. The following lifecycle hooks can be configured for a function instance: Initializer, PreFreeze, and PreStop hooks. In the PHP runtime environment, you can configure Initializer and PreStop hooks. For more information, see Function instance lifecycle.

The billing rules for the lifecycle hooks of function instances are the same as the billing rules for common invocation requests. However, the execution logs can be queried only in Function Logs, Instance Logs, or Advanced Logs. The logs for lifecycle hooks are not displayed in Call Request List. For more information, see View the logs of instance lifecycle hooks..

Initializer hooks

Example

An Initializer hook is executed after a function instance is started and before a handler runs. Function Compute ensures that an Initializer hook is successfully invoked at most once in the lifecycle of a function instance. For example, if an Initializer hook fails to be invoked, the system retries the Initializer hook until the Initializer hook is successfully invoked, and then runs your handler. Make sure that an Initializer hook is correctly configured when it is repeatedly invoked.

An Initializer hook has only one input parameter $context and can be used in the same manner as a handler.

The following sample code provides an example on a simple Initializer hook:

<?php
function my_initializer($context) {
    $logger = $GLOBALS['fcLogger'];
    $logger->info("hello world");
}
?>            

my_initializer is the method name of an Initializer hook. The name must be the same as the value of the Initializer Hook parameter that you configured in the Function Compute console. For example, if the value of the Initializer Hook parameter for the function is main.my_initializer, Function Compute loads the my_initializer method that is defined in main.php after the Initializer hook is configured.

Method signature

  • An initializer function has only one input parameter context. The information in this parameter is the same as that of the context parameter specified for a handler.
  • The initializer and initializationTimeout fields in the context parameter are used for Initializer hooks. When you use an Initializer hook, set the two fields to the values that you configure for the Initializer Hook and Initializer Timeout parameters of the function. Otherwise, the values are empty and do not take effect.
  • No value is returned.

PreStop hook

A PreStop hook is executed before a function instance is destroyed. The method signature of a PreStop hook is the same as that of an Initializer hook.

The following sample code provides an example on a PreStop hook:
<?php

$counter = 0;
function preStop($context) {
    $GLOBALS['fcLogger']->info("preStop ok");
}

function handler($event, $context) {
    global $counter;
    $counter += 2;
    return $counter;
}
?>
You can query the logs of the PreStop hook in the Logstore that you activated for the function. For example, you can use a statement in the following format to query all logs of the function. For more information, see Query logs related to hooks.
<funcName> AND <ServiceName> AND qualifier: <VERSION>

Configure lifecycle hooks

Use the Function Compute console

You can configure Initializer Hook and PreStop Hook in the function configurations in the Function Compute console. For more information, see Function instance lifecycle. The format of a hook is [File name.Method name]. Examples:
  • If you set Initializer Hook to index.initialize, the initialize method in the index.php file is used.
  • If you set PreStop Hook to index.preStop, the preStop method in the index.php file is used.
db-php-lifecycle

Use Serverless Devs

You can use Serverless Devs to configure lifecycle hooks. In this case, you must add the Initializer Hook and PreStop Hook to the s.yaml file.
  • Configure the Initializer hook

    Add the initializer and initializationTimeout fields to the function configurations.

  • Configure the PreStop hook

    Add the instanceLifecycleConfig.preStop field, including handler and timeout, to the function configurations.

Sample code:

edition: 1.0.0          #  The version of the YAML syntax. The version complies with the semantic versioning specification.
name: hello-world-app  #  The name of the project.
access: default         #  The alias of the key.

vars:
  region: cn-hangzhou
  service:
    name: php72-mysql    # The name of the service.
    description: 'hello world by serverless devs' # A brief description of the service.

services:
  helloworld: # The name of the service or module.
    component: fc
    props:
      region: ${vars.region}
      service: ${vars.service}
      function:
        name: php72-mysql                              # The name of the function.
        description: 'hello world by serverless devs' # A brief description of the function.
        runtime: php7.2                                # Runtime.
        codeUri: ./code                                # The location of the code.
        handler: index.handler                         # The handler of the function. The format of the value varies based on the programming language that you use.
        memorySize: 128                                # The memory size for the function.
        timeout: 60                                    # The timeout period for the execution of the function.
        initializationTimeout: 20                      # The timeout period for the execution of the Initializer method.
        initializer: index.initialize                  # The Initializer method.
        instanceLifecycleConfig:                       # The extension function.
          preStop:                                     # The PreStop hook.
            handler: index.pre_stop                    # The handler of the function.
            timeout: 20                                # The timeout period.

For more information about the YAML syntax of Serverless Devs, see Serverless Devs commands.

View the logs of instance lifecycle hooks.

You can view the logs for lifecycle hook in Function Logs.

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
  2. In the top navigation bar, select a region. On the Services page, click the desired service.
  3. On the Functions page, click the name of the desired function. On the Function Details page that appears, click the Test Function tab.
  4. On the Test Function tab, click Test Function. Choose Logs > Function Logs.
    On the Function Logs tab, you can view the invocation logs, and the logs for the Initializer hooks and PreFreeze hooks of the function. Example:
    2022-10-09 19:26:17 FunctionCompute dotnetcore3.1 runtime inited.
    2022-10-09 19:26:17 FC Initialize Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Initialize start
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle initializer: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Initialize end
    2022-10-09 19:26:17 FC Initialize End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC Invoke Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle request: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC Invoke End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC PreFreeze Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] PreFreeze start
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle PreFreeze: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] PreFreeze end
    2022-10-09 19:26:17 FC PreFreeze End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    Each function instance is cached for a period of time and not destroyed immediately, you cannot view the logs for PreStop hooks right away. To quickly trigger the PreStop hook, you can update the function configurations or function code. After the update is complete, you can view the logs for PreStop hooks in Function Logs. Example:
    2022-10-09 19:32:17 FC PreStop Start RequestId: 03be685c-378b-4736-8b08-a67c1d*****
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] PreStop start
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] Handle PreStop: 03be685c-378b-4736-8b08-a67c1d*****
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] PreStop end
    2022-10-09 19:32:17 FC PreStop End RequestId: 03be685c-378b-4736-8b08-a67c1d*****

Sample program

Function Compute provides a sample program on the MySQL database that uses an Initializer hook and a PreStop hook. In this example, the Initializer hook is used to obtain the MySQL database configurations from environment variables, create the MySQL database connections, and test the database connectivity. The PreStop hook is used to close the MySQL connection.

For more information, see php72-mysql.