Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Lambda Bundle Laravel Package

dayspring-tech/lambda-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dayspring-tech/lambda-bundle
    
  2. Dockerfile Integration Add this to your Dockerfile (place it after composer install):

    COPY vendor/dayspring-tech/lambda-bundle/Bootstrap/service.php /var/runtime/bootstrap
    RUN chmod +x /var/runtime/bootstrap
    
  3. First Lambda Handler Create a service implementing LambdaHandlerServiceInterface:

    // src/Service/MyLambdaHandler.php
    namespace App\Service;
    
    use DayspringTech\LambdaBundle\LambdaHandlerServiceInterface;
    
    class MyLambdaHandler implements LambdaHandlerServiceInterface
    {
        public function handle(array $event): array
        {
            return ['status' => 'success', 'data' => ['message' => 'Hello from Lambda!']];
        }
    }
    
  4. Register the Handler Tag it as a public service in config/services.yaml:

    services:
        App\Service\MyLambdaHandler:
            tags: ['lambda.handler']
    
  5. Deploy Build your Docker image and push to AWS ECR. Deploy via AWS Lambda with:

    • Runtime: provided.al2 (or equivalent)
    • Entry Point: /var/runtime/bootstrap
    • Handler: index.php (default entrypoint in the bundle)

Implementation Patterns

Workflow: Request-Response Lambda

  1. Event Handling The bundle automatically parses AWS Lambda events (e.g., APIGatewayProxyRequest). Access them via:

    public function handle(array $event): array
    {
        $request = $event['requestContext']['http'] ?? null;
        return ['body' => json_encode(['input' => $request['path']])];
    }
    
  2. Kernel Bootstrapping The Symfony kernel boots once per Lambda invocation (unlike Bref’s console-only approach). Leverage full Symfony features:

    public function handle(array $event)
    {
        $entityManager = $this->container->get('doctrine')->getManager();
        // Use Doctrine, services, etc.
    }
    
  3. Dependency Injection Inject services directly into your handler:

    use Symfony\Component\HttpFoundation\RequestStack;
    
    class MyLambdaHandler implements LambdaHandlerServiceInterface
    {
        public function __construct(private RequestStack $requestStack) {}
    
        public function handle(array $event): array
        {
            $request = $this->requestStack->getCurrentRequest();
            // ...
        }
    }
    
  4. Environment Awareness Use APP_ENV and APP_DEBUG via Symfony’s ParameterBagInterface:

    public function __construct(private ParameterBagInterface $params) {}
    
    public function handle(array $event): array
    {
        if ($this->params->get('kernel.debug')) {
            return ['debug' => true];
        }
        return ['debug' => false];
    }
    
  5. Error Handling Throw exceptions to return HTTP 500 responses:

    public function handle(array $event): array
    {
        if ($event['error']) {
            throw new \RuntimeException('Custom error message');
        }
        return [];
    }
    

Integration Tips

  • API Gateway Proxy Integration Use $event['body'] to access raw JSON payloads:

    $data = json_decode($event['body'], true);
    
  • S3 Event Triggers Parse S3 events:

    $bucket = $event['Records'][0]['s3']['bucket']['name'];
    $key = $event['Records'][0]['s3']['object']['key'];
    
  • DynamoDB Streams Access DynamoDB records:

    $dynamoEvent = $event['Records'][0]['dynamodb'];
    $newImage = $dynamoEvent['NewImage'];
    
  • Custom Runtime API Extend the runtime API by overriding Bootstrap/service.php:

    // Add custom initialization logic before kernel boot
    require __DIR__.'/../vendor/autoload.php';
    $customConfig = new CustomConfig();
    $kernel = new AppKernel('prod', $customConfig);
    

Gotchas and Tips

Pitfalls

  1. Cold Starts

    • Issue: Symfony kernel boot time adds ~500ms–1s to cold starts.
    • Fix: Use Provisioned Concurrency in AWS Lambda to keep instances warm.
  2. Memory Limits

    • Issue: Lambda’s 128MB–3GB memory limit may cause OutOfMemoryException for large payloads.
    • Fix: Monitor memory usage with memory_get_usage() and adjust Lambda memory settings.
  3. Circular Dependencies

    • Issue: Lambda handlers cannot be private services (must be public).
    • Fix: Use autowire: false and explicit constructor injection:
      services:
          App\Service\MyLambdaHandler:
              autowire: false
              public: true
      
  4. Event Parsing Quirks

    • Issue: Raw Lambda events may not match Symfony’s expectations (e.g., APIGatewayProxyRequest vs. raw JSON).
    • Fix: Validate input structure:
      if (!isset($event['body'])) {
          throw new \InvalidArgumentException('Missing event body');
      }
      
  5. Logging

    • Issue: Symfony’s monolog may not log to CloudWatch by default.
    • Fix: Configure the monolog handler in config/packages/monolog.yaml:
      handlers:
          main:
              type: stream
              path: php://stdout
              level: debug
              channels: ["!event"]
      

Debugging Tips

  1. Local Testing Use the bref CLI to test locally:

    composer require --dev bref/bref
    vendor/bin/bref run src/Service/MyLambdaHandler::handle
    
  2. X-Ray Tracing Enable AWS X-Ray for distributed tracing:

    // In your handler
    $this->container->get('aws.xray')->beginSegment('LambdaHandler');
    try {
        // Handle logic
    } finally {
        $this->container->get('aws.xray')->endSegment();
    }
    
  3. Environment Variables Access Lambda environment variables via Symfony’s ParameterBag:

    $this->params->get('MY_CUSTOM_VAR');
    
  4. Timeout Handling

    • Lambda’s max timeout is 15 minutes. Use set_time_limit() if needed:
      set_time_limit(900); // 15 minutes
      

Extension Points

  1. Custom Runtime Initialization Override Bootstrap/service.php to add pre-boot logic:

    // Example: Load custom environment variables
    putenv('CUSTOM_VAR=value');
    require __DIR__.'/../vendor/autoload.php';
    
  2. Handler Middleware Create a middleware stack for handlers:

    use DayspringTech\LambdaBundle\Middleware\LambdaMiddlewareInterface;
    
    class LoggingMiddleware implements LambdaMiddlewareInterface
    {
        public function handle(array $event, callable $next): array
        {
            error_log('Event received: '.json_encode($event));
            return $next($event);
        }
    }
    

    Register via tag:

    services:
        App\Middleware\LoggingMiddleware:
            tags: ['lambda.middleware']
    
  3. Kernel Events Dispatch Symfony events during Lambda execution:

    $this->container->get('event_dispatcher')->dispatch(
        new LambdaEvent($event),
        'lambda.handle'
    );
    
  4. Custom Response Formats Extend the response format by overriding the bundle’s ResponseFactory:

    use DayspringTech\LambdaBundle\Response\ResponseFactoryInterface;
    
    class CustomResponseFactory implements ResponseFactoryInterface
    {
        public function create(array $data, int $status = 200): array
        {
            return [
                'statusCode' => $status,
                'body' => json_encode($data),
                'headers' => ['Content-Type' => 'application/json'],
                'customField' => 'value' // Extend response
            ];
        }
    }
    

    Bind it in config/services.yaml:

    services:
        DayspringTech\LambdaBundle\Response\ResponseFactoryInterface: '@App\Response\CustomResponseFactory'
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware