关于 aws-lambda-php-integration
aws-lambda-php-integration 汇集使用 Bref 或原生 PHP 在 AWS Lambda 上部署 PHP 与 Symfony 应用的模式,面向构建和迁移 Lambda 项目的开发者。内容涵盖 API Gateway 集成、冷启动优化和部署配置。
主要功能
- 01提供 Bref 与原生 PHP 两种方案
- 02说明 Symfony 应用的 Lambda 结构
- 03涵盖 API Gateway 与事件触发器配置
- 04列出冷启动优化和连接管理做法
- 05包含部署、测试与安全建议
适用场景
- 01将 Symfony 应用迁移到 AWS Lambda
- 02构建 PHP Lambda 函数和 API
- 03优化冷启动并配置部署流程
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ giuseppe-trisciuoglio/ developer-kit --skill aws-lambda-php-integration安装后在 Claude Code 中输入/aws-lambda-php-integration确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/best-practices.mdbref-lambda.mdexamples.mdpatterns.mdraw-php-lambda.mdserverless-deployment.mdtesting-lambda.md详细介绍
AWS Lambda PHP 集成
使用 Bref 框架在 AWS Lambda 上部署 PHP 和 Symfony 应用的模式。
概述
有两种可用方案:
- Bref 框架 - 在 Lambda 上运行标准 PHP,支持 Symfony,内置路由,冷启动时间 < 2s
- 原生 PHP - 开销最小,控制力最大,冷启动时间 < 500ms
两种方案都支持与 API Gateway 集成,并提供可用于生产环境的配置。
适用场景
- 创建新的 PHP Lambda 函数
- 将现有 Symfony 应用迁移到 Lambda
- 优化冷启动性能
- 配置 API Gateway 或 SQS/SNS 事件触发器
- 为 PHP Lambda 设置部署流水线
说明
1. 选择方案
| 方案 | 冷启动时间 | 最适合 | 复杂度 |
|---|---|---|---|
| Bref | < 2s | Symfony 应用、功能齐全的 API | 中 |
| 原生 PHP | < 500ms | 简单处理程序、最大控制力 | 低 |
2. 项目结构
使用 Bref 的 Symfony 结构
my-symfony-lambda/
├── composer.json
├── serverless.yml
├── public/
│ └── index.php # Lambda entry point
├── src/
│ └── Kernel.php # Symfony Kernel
├── config/
│ ├── bundles.php
│ ├── routes.yaml
│ └── services.yaml
└── templates/
原生 PHP 结构
my-lambda-function/
├── public/
│ └── index.php # Handler entry point
├── composer.json
├── serverless.yml
└── src/
└── Services/
3. 实现
使用 Bref 的 Symfony:
// public/index.php
use Bref\Symfony\Bref;
use App\Kernel;
use Symfony\Component\HttpFoundation\Request;
require __DIR__.'/../vendor/autoload.php';
$kernel = new Kernel($_SERVER['APP_ENV'] ?? 'dev', $_SERVER['APP_DEBUG'] ?? true);
$kernel->boot();
$bref = new Bref($kernel);
return $bref->run($event, $context);
原生 PHP 处理程序:
// public/index.php
use function Bref\Lambda\main;
main(function ($event) {
$path = $event['path'] ?? '/';
$method = $event['httpMethod'] ?? 'GET';
return [
'statusCode' => 200,
'body' => json_encode(['message' => 'Hello from PHP Lambda!'])
];
});
4. 冷启动优化
- 延迟加载 - 按需加载重量级服务
- 禁用未使用的 Symfony 功能 - 关闭验证和注解
- 优化 Composer 自动加载 - 在生产环境中使用 classmap
- 使用 Bref 优化运行时 - 利用 PHP 8.x 优化
5. 连接管理
// Cache AWS clients at function level
use Aws\DynamoDb\DynamoDbClient;
class DatabaseService
{
private static ?DynamoDbClient $client = null;
public static function getClient(): DynamoDbClient
{
if (self::$client === null) {
self::$client = new DynamoDbClient([
'region' => getenv('AWS_REGION'),
'version' => 'latest'
]);
}
return self::$client;
}
}
最佳实践
内存和超时
- 内存:Symfony 从 512MB 开始,原生 PHP 从 256MB 开始
- 超时:Symfony 使用 10-30s 为冷启动预留缓冲时间;原生 PHP 通常 3-10s 就足够
依赖项
{
"require": {
"php": "^8.2",
"bref/bref": "^2.0",
"symfony/framework-bundle": "^6.0"
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist"
}
}
错误处理
try {
$result = processRequest($event);
return [
'statusCode' => 200,
'body' => json_encode($result)
];
} catch (ValidationException $e) {
return [
'statusCode' => 400,
'body' => json_encode(['error' => $e->getMessage()])
];
} catch (Exception $e) {
error_log($e->getMessage());
return [
'statusCode' => 500,
'body' => json_encode(['error' => 'Internal error'])
];
}
日志记录
error_log(json_encode([
'level' => 'info',
'message' => 'Request processed',
'request_id' => $context->getAwsRequestId(),
'path' => $event['path'] ?? '/'
]));
部署
Serverless 配置
# serverless.yml
service: symfony-lambda-api
provider:
name: aws
runtime: php-82
memorySize: 512
timeout: 20
package:
individually: true
exclude:
- '**/node_modules/**'
- '**/.git/**'
functions:
api:
handler: public/index.php
events:
- http:
path: /{proxy+}
method: ANY
部署和验证
# 1. Install Bref
composer require bref/bref --dev
# 2. Test locally (validate before deploy)
sam local invoke -e event.json
# 3. Deploy
vendor/bin/bref deploy
# 4. Verify deployment
aws lambda invoke --function-name symfony-lambda-api-api \
--payload '{"path": "/", "httpMethod": "GET"}' /dev/stdout
Symfony 完整配置
# serverless.yml for Symfony
service: symfony-lambda-api
provider:
name: aws
runtime: php-82
stage: ${self:custom.stage}
region: ${self:custom.region}
environment:
APP_ENV: ${self:custom.stage}
APP_DEBUG: ${self:custom.isLocal}
iam:
role:
statements:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
Resource: '*'
functions:
web:
handler: public/index.php
timeout: 30
memorySize: 1024
events:
- http:
path: /{proxy+}
method: ANY
console:
handler: bin/console
timeout: 300
events:
- schedule: rate(1 day)
plugins:
- ./vendor/bref/bref
custom:
stage: dev
region: us-east-1
isLocal: false
限制和警告
Lambda 限制
- 部署包:解压后最大 250MB(压缩后 50MB)
- 内存:128MB 到 10GB
- 超时:API Gateway 为 29 秒,异步调用为 15 分钟
- 并发执行数:默认 1000
PHP 特定注意事项
- 冷启动:PHP 的冷启动时间中等;使用 Bref 优化运行时
- 依赖项:保持 composer.json 精简;对共享依赖项使用 Lambda Layers
- PHP 版本:使用 PHP 8.2+ 以获得最佳 Lambda 性能
- 无本地存储:Lambda 容器是临时的;使用 S3/DynamoDB 持久化数据
常见问题
- vendor 文件夹过大 - 排除开发依赖项;使用 --no-dev
- 会话存储 - 不要使用本地文件存储;改用 DynamoDB
- 长时间运行的进程 - 不适用于 Lambda;请改用 ECS
- WebSocket - 请改用 API Gateway WebSockets 或 AppSync
安全注意事项
- 切勿硬编码凭证;使用 IAM 角色和 SSM Parameter Store
- 验证所有输入数据
- 使用最小权限 IAM 策略
- 启用 CloudTrail 进行审计日志记录
- 设置正确的 CORS 标头
示例
示例 1:创建 Symfony Lambda API
输入:“使用 Bref 为待办事项应用创建 Symfony Lambda REST API”
流程:
- 使用
composer create-project初始化 Symfony 项目 - 安装 Bref:
composer require bref/bref - 配置 serverless.yml
- 在 config/routes.yaml 中设置路由
- 本地测试:
sam local invoke - 部署:
vendor/bin/bref deploy - 验证:
aws lambda invoke --function-name <name> --payload '{}'
**输出:**完整的 Symfony 项目结构,包含 REST API、DynamoDB 集成和部署配置
示例 2:优化 Symfony 冷启动
输入:“我的 Symfony Lambda 冷启动需要 5 秒,该如何优化?”
流程:
- 分析启动时加载的服务
- 禁用未使用的 Symfony 功能(验证、注解)
- 对重量级服务使用延迟加载
- 优化 Composer 自动加载
- 测量:部署并调用以验证冷启动时间 < 2s
**输出:**重构后的 Symfony 配置,冷启动时间 < 2s
示例 3:使用 GitHub Actions 部署
输入:“为 Symfony Lambda 配置 Serverless Framework CI/CD”
流程:
- 创建 GitHub Actions 工作流
- 使用 composer 设置 PHP 环境
- 运行 PHPUnit 测试
- 使用 Serverless Framework 部署
- 验证:检查 Lambda 函数是否存在并能正常响应
**输出:**完整的 .github/workflows/deploy.yml,包含多阶段流水线和自动化测试
参考资料
- Bref Lambda - 完整的 Bref 设置、Symfony 集成和路由配置
- Raw PHP Lambda - 最简处理程序模式、缓存和打包
- Serverless Deployment - Serverless Framework、SAM 和 CI/CD 流水线
- Testing Lambda - PHPUnit、SAM Local 和集成测试
评论
支持 Markdown