aws-lambda-php-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS Lambda PHP Integration

AWS Lambda PHP集成方案

Patterns for deploying PHP and Symfony applications on AWS Lambda using the Bref framework.
基于Bref框架在AWS Lambda上部署PHP与Symfony应用的实现方案。

Overview

概述

This skill provides complete patterns for AWS Lambda PHP development with two main approaches:
  1. Bref Framework - The standard solution for PHP on Lambda with Symfony support, built-in routing, and cold start optimization
  2. Raw PHP - Minimal overhead approach with maximum control
Both approaches support API Gateway integration with production-ready configurations.
本方案提供两种AWS Lambda PHP开发的完整实现方式:
  1. Bref框架 - PHP在Lambda上的标准解决方案,支持Symfony,内置路由功能,且具备冷启动优化特性
  2. 原生PHP - 开销极小的实现方式,可实现最大程度的控制
两种方式均支持与API Gateway的集成,且配置可直接用于生产环境。

When to Use

适用场景

Use this skill when:
  • Creating new Lambda functions in PHP
  • Migrating existing Symfony applications to Lambda
  • Optimizing cold start performance for PHP Lambda
  • Choosing between Bref-based and minimal PHP approaches
  • Configuring API Gateway integration
  • Setting up deployment pipelines for PHP Lambda
适用于以下场景:
  • 用PHP创建新的Lambda函数
  • 将现有Symfony应用迁移到Lambda
  • 优化PHP Lambda的冷启动性能
  • 在基于Bref的方案与原生PHP方案之间做选择
  • 配置API Gateway集成
  • 为PHP Lambda设置部署流水线

Instructions

操作指南

1. Choose Your Approach

1. 选择方案

ApproachCold StartBest ForComplexity
Bref< 2sSymfony apps, full-featured APIsMedium
Raw PHP< 500msSimple handlers, maximum controlLow
方案冷启动时间适用场景复杂度
Bref< 2秒Symfony应用、功能完整的API中等
原生PHP< 500毫秒简单处理器、需要最大程度控制

2. Project Structure

2. 项目结构

Symfony with Bref Structure

基于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/
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/

Raw PHP Structure

原生PHP项目结构

my-lambda-function/
├── public/
│   └── index.php         # Handler entry point
├── composer.json
├── serverless.yml
└── src/
    └── Services/
my-lambda-function/
├── public/
│   └── index.php         # Handler entry point
├── composer.json
├── serverless.yml
└── src/
    └── Services/

3. Implementation Examples

3. 实现示例

Symfony with Bref:
php
// 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);
Raw PHP Handler:
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!'])
    ];
});
基于Bref的Symfony实现:
php
// 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处理器:
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!'])
    ];
});

Core Concepts

核心概念

Cold Start Optimization

冷启动优化

PHP cold start depends on framework initialization. Key strategies:
  1. Lazy loading - Defer heavy services until needed
  2. Disable unused Symfony features - Turn off validation, annotations, etc.
  3. Optimize composer autoload - Use classmap for production
  4. Use Bref optimized runtime - Leverage PHP 8.x optimizations
PHP的冷启动时间取决于框架初始化速度。关键优化策略:
  1. 延迟加载 - 延迟加载重型服务,直到需要时再初始化
  2. 禁用未使用的Symfony功能 - 关闭验证、注解等未使用的功能
  3. 优化Composer自动加载 - 生产环境使用类映射(classmap)
  4. 使用Bref优化的运行时 - 利用PHP 8.x的优化特性

Connection Management

连接管理

php
// 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;
    }
}
php
// 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;
    }
}

Environment Configuration

环境配置

php
// config/services.yaml
parameters:
    env(DATABASE_URL): null
    env(APP_ENV): 'dev'

services:
    App\Service\Configuration:
        arguments:
            $tableName: '%env(DATABASE_URL)%'
php
// config/services.yaml
parameters:
    env(DATABASE_URL): null
    env(APP_ENV): 'dev'

services:
    App\Service\Configuration:
        arguments:
            $tableName: '%env(DATABASE_URL)%'

Best Practices

最佳实践

Memory and Timeout Configuration

内存与超时配置

  • Memory: Start with 512MB for Symfony, 256MB for raw PHP
  • Timeout: Set based on expected processing time
    • Symfony: 10-30 seconds for cold start buffer
    • Raw PHP: 3-10 seconds typically sufficient
  • 内存:Symfony应用初始设置512MB,原生PHP应用初始设置256MB
  • 超时:根据预期处理时间设置
    • Symfony:为冷启动预留缓冲,设置10-30秒
    • 原生PHP:通常设置3-10秒即可

Dependencies

依赖管理

Keep
composer.json
minimal:
json
{
    "require": {
        "php": "^8.2",
        "bref/bref": "^2.0",
        "symfony/framework-bundle": "^6.0"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist"
    }
}
保持
composer.json
精简:
json
{
    "require": {
        "php": "^8.2",
        "bref/bref": "^2.0",
        "symfony/framework-bundle": "^6.0"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist"
    }
}

Error Handling

错误处理

Return proper Lambda responses:
php
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'])
    ];
}
返回标准的Lambda响应:
php
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'])
    ];
}

Logging

日志记录

Use structured logging:
php
error_log(json_encode([
    'level' => 'info',
    'message' => 'Request processed',
    'request_id' => $context->getAwsRequestId(),
    'path' => $event['path'] ?? '/'
]));
使用结构化日志:
php
error_log(json_encode([
    'level' => 'info',
    'message' => 'Request processed',
    'request_id' => $context->getAwsRequestId(),
    'path' => $event['path'] ?? '/'
]));

Deployment Options

部署选项

Quick Start

快速开始

Serverless Framework:
yaml
undefined
Serverless Framework配置:
yaml
undefined

serverless.yml

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 - http: path: / method: ANY

**Deploy with Bref:**
```bash
composer require bref/bref --dev
vendor/bin/bref deploy
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 - http: path: / method: ANY

**使用Bref部署:**
```bash
composer require bref/bref --dev
vendor/bin/bref deploy

Symfony Full Configuration

Symfony完整配置

yaml
undefined
yaml
undefined

serverless.yml for 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
undefined
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
undefined

Constraints and Warnings

限制与注意事项

Lambda Limits

Lambda限制

  • Deployment package: 250MB unzipped maximum (50MB zipped)
  • Memory: 128MB to 10GB
  • Timeout: 29 seconds (API Gateway), 15 minutes for async
  • Concurrent executions: 1000 default
  • 部署包:最大250MB(解压后),压缩后最大50MB
  • 内存:128MB到10GB
  • 超时:API Gateway触发的函数最大29秒,异步函数最大15分钟
  • 并发执行数:默认1000个

PHP-Specific Considerations

PHP专属注意事项

  • Cold start: PHP has moderate cold start; use Bref for optimized runtimes
  • Dependencies: Keep composer.json minimal; use Lambda Layers for shared deps
  • PHP version: Use PHP 8.2+ for best Lambda performance
  • No local storage: Lambda containers are ephemeral; use S3/DynamoDB for persistence
  • 冷启动:PHP的冷启动时间中等;使用Bref优化的运行时可改善
  • 依赖:保持composer.json精简;使用Lambda Layers管理共享依赖
  • PHP版本:使用PHP 8.2+以获得最佳Lambda性能
  • 无本地存储:Lambda容器是临时的;使用S3或DynamoDB进行持久化存储

Common Pitfalls

常见陷阱

  1. Large vendor folder - Exclude dev dependencies; use --no-dev
  2. Session storage - Don't use local file storage; use DynamoDB
  3. Long-running processes - Not suitable for Lambda; use ECS instead
  4. Websockets - Use API Gateway WebSockets or AppSync instead
  1. 庞大的vendor目录 - 排除开发依赖;使用--no-dev参数
  2. 会话存储 - 不要使用本地文件存储;使用DynamoDB
  3. 长运行进程 - Lambda不适合长运行进程;改用ECS
  4. WebSockets - 使用API Gateway WebSockets或AppSync替代

Security Considerations

安全注意事项

  • Never hardcode credentials; use IAM roles and SSM Parameter Store
  • Validate all input data
  • Use least privilege IAM policies
  • Enable CloudTrail for audit logging
  • Set proper CORS headers
  • 切勿硬编码凭证;使用IAM角色和SSM参数存储
  • 验证所有输入数据
  • 使用最小权限原则配置IAM策略
  • 启用CloudTrail进行审计日志
  • 设置正确的CORS头

References

参考资料

For detailed guidance on specific topics:
  • Bref Lambda - Complete Bref setup, Symfony integration, routing
  • Raw PHP Lambda - Minimal handler patterns, caching, packaging
  • Serverless Deployment - Serverless Framework, SAM, CI/CD pipelines
  • Testing Lambda - PHPUnit, SAM Local, integration testing
如需特定主题的详细指导:
  • Bref Lambda - 完整的Bref设置、Symfony集成、路由配置
  • 原生PHP Lambda - 极简处理器方案、缓存、打包
  • 无服务器部署 - Serverless Framework、SAM、CI/CD流水线
  • Lambda测试 - PHPUnit、SAM Local、集成测试

Examples

示例

Example 1: Create a Symfony Lambda API

示例1:创建Symfony Lambda API

Input:
Create a Symfony Lambda REST API using Bref for a todo application
Process:
  1. Initialize Symfony project with
    composer create-project
  2. Install Bref:
    composer require bref/bref
  3. Configure serverless.yml
  4. Set up routes in config/routes.yaml
  5. Configure deployment with
    vendor/bin/bref deploy
Output:
  • Complete Symfony project structure
  • REST API with CRUD endpoints
  • DynamoDB integration
  • Deployment configuration
输入:
Create a Symfony Lambda REST API using Bref for a todo application
步骤:
  1. 使用
    composer create-project
    初始化Symfony项目
  2. 安装Bref:
    composer require bref/bref
  3. 配置serverless.yml
  4. 在config/routes.yaml中设置路由
  5. 使用
    vendor/bin/bref deploy
    完成部署
输出:
  • 完整的Symfony项目结构
  • 具备CRUD接口的REST API
  • 与DynamoDB的集成配置
  • 部署配置文件

Example 2: Optimize Cold Start for Symfony

示例2:优化Symfony的冷启动性能

Input:
My Symfony Lambda has 5 second cold start, how do I optimize it?
Process:
  1. Analyze services loaded at startup
  2. Disable unused Symfony features (validation, annotations)
  3. Use lazy loading for heavy services
  4. Optimize composer autoload
  5. Consider using raw PHP if full framework not needed
Output:
  • Refactored Symfony configuration
  • Optimized cold start < 2s
  • Service analysis report
输入:
My Symfony Lambda has 5 second cold start, how do I optimize it?
步骤:
  1. 分析启动时加载的服务
  2. 禁用未使用的Symfony功能(验证、注解等)
  3. 对重型服务使用延迟加载
  4. 优化Composer自动加载
  5. 如果不需要完整框架,考虑使用原生PHP方案
输出:
  • 重构后的Symfony配置
  • 优化后冷启动时间<2秒
  • 服务分析报告

Example 3: Deploy with GitHub Actions

示例3:使用GitHub Actions部署

Input:
Configure CI/CD for Symfony Lambda with Serverless Framework
Process:
  1. Create GitHub Actions workflow
  2. Set up PHP environment with composer
  3. Run PHPUnit tests
  4. Deploy with Serverless Framework
  5. Configure environment protection for prod
Output:
  • Complete .github/workflows/deploy.yml
  • Multi-stage pipeline
  • Integrated test automation
输入:
Configure CI/CD for Symfony Lambda with Serverless Framework
步骤:
  1. 创建GitHub Actions工作流
  2. 配置带Composer的PHP环境
  3. 运行PHPUnit测试
  4. 使用Serverless Framework部署
  5. 为生产环境配置环境保护
输出:
  • 完整的.github/workflows/deploy.yml
  • 多阶段部署流水线
  • 集成测试自动化配置

Version

版本

Version: 1.0.0
Version: 1.0.0