This topic describes how to implement and use instance lifecycle hook methods in PHP.
Background information
When you implement and configure an instance lifecycle hook, Function Compute calls the corresponding hook when a lifecycle event occurs. The PHP runtime supports Initializer and PreStop instance lifecycle hooks. For more information, see Configure instance lifecycles.
Billing for instance lifecycle hooks is the same as for regular function invocations. However, their execution logs appear only in Real-time Logs, Function Logs, or Advanced Logs. The Invocation Request List does not display logs for hooks. For more information, see View instance lifecycle hook logs.
Initializer hook
Initializer Example
An Initializer hook runs after a function instance starts and before the handler runs. Function Compute ensures that an Initializer hook runs successfully only once during the lifecycle of an instance. If the Initializer hook fails to run, the function invocation fails. On the next invocation, Function Compute creates a new instance to run the initializer hook.
When an initializer hook times out or fails, the server always returns an HTTP 200 status code. To determine if an initialization failure caused the error, check the X-Fc-Error-Type:InitializationError response header or the errorMessage field in the response body.
The Initializer hook has only one input parameter, $context, which is used in the same way as a handler.
The following code shows a simple Initializer hook example.
<?php
function my_initializer($context) {
$logger = $GLOBALS['fcLogger'];
$logger->info("hello world");
}
?> my_initializer is the name of the Initializer callback method, which must match the Initializer Hook that you configure in the Function Compute console. For example, if you set the Initializer Hook for your function to main.my_initializer, Function Compute loads the my_initializer method that is defined in main.php after the Initializer property is configured.
Method Signature
The only input parameter is
context. The information in this parameter is the same as that in thecontextparameter for a handler.The
contextfieldsinitializerandinitializationTimeoutare designed for the Initializer hook. If you use an Initializer hook, these fields are set to the values of the Initializer Hook and Initializer Hook Timeout that you configure for your function. Otherwise, the fields are empty and the hook does not take effect.No value is returned.
PreStop hook
A PreStop hook runs before a function instance is destroyed. Its method signature is the same as that of an Initializer hook.
The following code shows a PreStop hook example.
<?php
$counter = 0;
function preStop($context) {
$GLOBALS['fcLogger']->info("preStop ok");
}
function handler($event, $context) {
global $counter;
$counter += 2;
return $counter;
}
?>You can query logs for the PreStop hook in the Logstore that you enabled for the function. For example, you can use a statement in the following format to query all logs for the function. For more information, see Query logs related to hooks.
<funcName> AND <ServiceName> AND qualifier: <VERSION>Configure lifecycle hooks
Configure Using The Console
In the Function Compute console, navigate to the tab for your FC function to configure the Initializer Hook and PreStop Hook. For more information, see Configure instance lifecycles. The format for a hook is [File name.Method name]. The following are examples:
If you set Initializer Hook to
index.initialize, it indicates theinitializemethod in theindex.phpfile.If you set PreStop Hook to
index.preStop, it indicates thepreStopmethod in theindex.phpfile.
Use Serverless Devs
If you use Serverless Devs, add the Initializer Hook and PreStop Hook configurations to the s.yaml file.
Initializer hook:
Add the instanceLifecycleConfig.initializer field under the function configuration. This field includes the handler and timeout properties.
PreStop hook:
Add the instanceLifecycleConfig.preStop field under the function configuration. This field includes the handler and timeout properties.
The following code shows an example.
edition: 3.0.0
name: fcDeployApp
access: "default"
vars: # Global variables
region: "cn-hangzhou"
resources:
hello_world:
component: fc3 # Component name
props:
region: ${vars.region} # For more information about how to use variables, see https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC
functionName: "testphp"
description: 'this is a test'
runtime: "php7.2"
code: ./
handler: index.handler
memorySize: 128
timeout: 30
instanceLifecycleConfig: # Extension function
initializer: # Initializer hook
handler: index.my_initializer
timeout: 60
preStop: # PreStop hook
handler: index.preStop # Handler
timeout: 60 # Timeout period
For more information about the YAML syntax for Serverless Devs, see Common Serverless Devs commands.
View the logs of instance lifecycle hooks
You can view the logs for lifecycle hook in Logs.
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Test Function tab, click Test Function, and then choose .
On the Logs tab, you can view function invocation logs and Initializer logs. Example:
2024-03-04 17:57:28FC Initialize Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69 2024-03-04 17:57:282024-03-04 09:57:28.192 1-65e59b07-1520da26-bf73bbb91b69 [info] initializer 2024-03-04 17:57:28FC Initialize End RequestId: 1-65e59b07-1520da26-bf73bbb91b69 2024-03-04 17:57:28FC Invoke Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69 2024-03-04 17:57:28FC Invoke End RequestId: 1-65e59b07-1520da26-bf73bbb91b69Each function instance is cached for a period of time and not immediately destroyed, you cannot view logs for PreStop hooks right away. To quickly trigger a 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. The following sample code shows an example:
2024-03-04 18:33:26FC PreStop Start RequestId: 93c93603-9fbe-4576-9458-193c8b213031 2024-03-04 18:33:262024-03-04 10:33:26.077 93c93603-9fbe-4576-9458-193c8b213031 [info] preStop 2024-03-04 18:33:26FC PreStop End RequestId: 93c93603-9fbe-4576-9458-193c8b213031
Sample program
Function Compute provides a sample MySQL program that uses Initializer and PreStop hooks. In this example, the Initializer hook retrieves the MySQL database configuration from environment variables, creates a connection to the MySQL database, and then tests the connectivity. The PreStop hook closes the MySQL connection. For more information, see php72-mysql.