videlalvaro/azserverless

"Azure Functions的PHP自定义处理器"

dev-main 2020-11-18 06:55 UTC

This package is auto-updated.

Last update: 2024-09-18 15:36:17 UTC


README

此项目为Azure Functions提供了一个PHP 自定义处理器

安装

在你的composer.json中添加以下依赖项

"require": {
        "videlalvaro/azserverless": "*"
}

然后运行

composer update

然后启动一个Azure Functions项目。在你的host.json中添加以下内容

"customHandler": {
    "description": {
        "defaultExecutablePath": "php",
        "arguments": [
            "-S",
            "0.0.0.0:%FUNCTIONS_CUSTOMHANDLER_PORT%",
            "vendor/videlalvaro/azserverless/bin/serverless.php"
        ]
    },
    "enableForwardingHttpRequest": false
},

请参阅host.sample.json,了解此文件应该如何看起来。

最后,将文件local.settings.sample.json复制到你的项目中,并将其命名为local.settings.json。根据需要在AzureWebJobsStorage字段中包含你的连接字符串。

使用方法

在你的Azure Functions项目中,每个无服务器函数将有一个对应的文件夹。

要创建一个名为HttpTrigger的函数,创建一个同名文件夹,然后在该文件夹内添加两个文件:function.jsonindex.php。以下是它们的内容

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

以及对应的index.php文件

<?php
use Azserverless\Context\FunctionContext;

function run(FunctionContext $context) {

    $req = $context->inputs['req'];

    $context->log->info('Http trigger invoked');

    $query = json_decode($req['Query'], true);

    if (array_key_exists('name', $query)) {
        $message = 'Hello ' . $query['name'] . '!';
    } else {
        $message = 'Please pass a name in the query string';
    }

    return [
        'body' => $message,
        'headers' => [
            'Content-type' => 'text/plain'
        ]
    ];
}
?>

如你所见,函数提供了一个FunctionContext对象,其中可以访问request数据,并且还可以将信息记录到控制台。

要了解更多关于Azure无服务器功能的详细信息,请参阅Azure Functions文档

部署

按照以下说明启用PHP 7.4,并在将函数应用程序部署到Azure时运行composer:[配置Azure App Service中的PHP应用程序](https://docs.microsoft.com/azure/app-service/configure-language-php?pivots=platform-windows&WT.mc_id=data-11039-alvidela#set-php-version)

当Azure CLI选项需要--name选项时,提供你的Azure Functions应用程序名称。