定制 tkotosz/fn-fdk-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

tkotosz/fn-fdk-php

Composer 安装命令:

composer require tkotosz/fn-fdk-php

包简介

PHP Function Development Kit for Fn

关键字:

README 文档

README

fn-fdk-go provides convenience functions for writing php fn code

Installing fn-fdk-php

You can install it manually with composer:

composer require tkotosz/fn-fdk-php

Or just use the php init image to create new funtion like this:

fn init --init-image tkotosz/fn-php-init myfunc

This will generate the necessary files for your function including the composer json and docker file to install this fdk.

Creating a PHP Function

Writing a PHP function is simply a matter of writing a handler function that you pass to the FDK to invoke each time your function is called.

Start by creating a php function with fn init:

fn init --init-image tkotosz/fn-php-init phpfunc
cd phpfunc

This creates a simple hello world function in func.php:

<?php

require('vendor/autoload.php');

$fdk = new Tkotosz\FnPhpFdk\Fdk();

$fdk->handle(function ($input) {
    $name = 'World';
    if (isset($input['name'])) {
        $name = $input['name'];
    }
    return ['message' => 'Hello ' . $name];
});

The handler function takes the input that is sent to the function and returns a response. By default the input is treated as json which automatically converted to an array and the response is also an array (or json serializable object) which automatically converted to json. Using the FDK you don't have to worry about reading the http request or sending back the response. The FDK let's you focus on your function logic and not the mechanics.

Now run it!

fn deploy --local --app fdkdemo 
fn invoke fdkdemo phpfunc 

You should see the following output:

{"message":"Hello World"}

Run it with input:

echo -n '{"name":"Tibor"}' | fn invoke fdkdemo phpfunc

You should see the following output:

{"message":"Hello Tibor"}

Now you have a basic running php function that you can modify and add what you want.

Function Context

Function invocation context details are available through an optional function argument. To receive a context object, simply add a second argument to your handler function. In the following example the callId is obtained from the context and included in the response message:

<?php

require('vendor/autoload.php');

$fdk = new Tkotosz\FnPhpFdk\Fdk();

$fdk->handle(function ($input, $ctx) {
    $name = 'World';
    if (isset($input['name'])) {
        $name = $input['name'];
    }
    return ['message' => 'Hello ' . $name, 'callId' => $ctx->getCallId()];
});

Run it:

echo -n '{"name":"Tibor"}' | fn invoke fdkdemo phpfunc

You should see a similar output:

{"message":"Hello Tibor","callId":"01D0F7QX2QNG8G00GZJ00001YV"}

The context contains other context information about the request such as:

  • ctx->getConfig : An object containing function config variables (from the environment variables)
  • ctx->getHeaders : An object containing input headers for the event as lists of strings
  • ctx->getDeadline : A DateTimeImmutable object indicating when the function call must be processed by
  • ctx->getCallId : The call ID of the current call
  • ctx->getId : The function ID of the current function
  • ctx->getMemory : Amount of ram in MB allocated to this function
  • ctx->getContentType : The incoming request content type (if set, otherwise null)
  • ctx->setResponseHeader(key,values...) : Sets a response header to one or more values
  • ctx->addResponseHeader(key,values...) : Appends values to an existing response header
  • ctx->responseContentType : Sets the response content type of the function
  • ctx->setResponseStatus : Sets the response status code of the function (default: 200)

Handling input/output

By default the FDK will try to json decode the input, likewise by default the output of a function will be treated as a JSON object and converted using json_encode().

To change the handling of the input you can add an additional options parameter to fdk->handle that specifies the input handling strategy:

$fdk->handle(function ($input) use ($fdk) {
    return ['message' => 'Hello ' . ($input ?: 'World')];
}, ['inputMode' => 'string']);

valid input modes are:

  • json (the default) attempts to parse the input as json
  • string always treats input as a string
  • stream passes the input stream (streaming request body) to your function

To change the output handling of your function from the default you should wrap the result value using a response decorator:

$fdk->handle(function ($input) use ($fdk) {
    return $fdk->rawResult('Hello '. ($input ?: 'World'));
}, ['inputMode' => 'string']);

the available decorators are:

  • rawResult({string|ReadableStreamInterface}) passes the result directly to the response - the value can be a string or a readable stream
  • streamResult({resource|ReadableStreamInterface}) pipes the contents of the resource or ReadableStreamInterface into the output - this allows processing of data from files or HTTP responses

Using HTTP headers and setting HTTP status codes

You can read http headers passed into a function invocation using $ctx->getHeaderValue($key), this returns the first header value of the header matching key or you can use $ctx->getHeaders() or $ctx->getHeaderValues($key) methods as well.

$fdk->handle(function ($input, $context) use ($fdk) {
    return $context->getHeaders(); // this will return all request headers as json
}, ['inputMode' => 'string']);

Outbound headers and the HTTP status code can be modified in a similar way:

$fdk->handle(function ($input, $context) {
    $context->setResponseStatus(201);
    $context->setResponseContentType('text/plain');
    $context->setResponseHeader('X-Awesomeness-level', 100);
    $context->addResponseHeader('X-Awesome-number', 1);
    $context->addResponseHeader('X-Awesome-number', 2);
    return 'Hello '. ($input ?: 'World');
}, ['inputMode' => 'string']);

Examples

See examples here.

tkotosz/fn-fdk-php 适用场景与选型建议

tkotosz/fn-fdk-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 24 次下载、GitHub Stars 达 6, 最近一次更新时间为 2019 年 01 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「fn」 「fdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 tkotosz/fn-fdk-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 tkotosz/fn-fdk-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 tkotosz/fn-fdk-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 24
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-01-05