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

Sidecar Laravel Package

hammerstone/sidecar

Sidecar lets Laravel package, deploy, and invoke AWS Lambda functions directly from your app. Define a simple PHP class plus the files to ship, choose any supported runtime (Node, Python, Java, .NET, Ruby, or OS-only), and execute from PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require hammerstone/sidecar
    php artisan sidecar:configure
    
    • Follow prompts to set AWS credentials (IAM user with Lambda permissions).
  2. First Function: Create a PHP class extending LambdaFunction (e.g., app/Sidecar/ExampleFunction.php):

    namespace App\Sidecar;
    
    use Hammerstone\Sidecar\LambdaFunction;
    
    class ExampleFunction extends LambdaFunction
    {
        public function handler() { return 'handler.handler'; }
        public function package() { return ['resources/lambda']; }
    }
    
  3. Handler File: Add a runtime-specific handler (e.g., resources/lambda/handler.js):

    exports.handler = async (event) => {
        return { message: 'Hello from Lambda!' };
    };
    
  4. Deploy & Execute:

    php artisan sidecar:deploy --activate
    
    // In a route/controller
    $result = ExampleFunction::execute(['key' => 'value']);
    

Key First Use Case

Image Generation:

  • Use Node.js/Python to generate images dynamically (e.g., OG tags) without server-side dependencies.
  • Deploy a Lambda function with canvas or Pillow libraries, then call it from Laravel routes.

Implementation Patterns

Core Workflows

  1. Function Development:

    • Multi-Runtime Support: Use runtime() method to specify runtime (e.g., Node::V20, Python::V3_12).
    • Environment Variables:
      public function environment() { return ['KEY' => 'value']; }
      
    • Memory/Timeout:
      public function memory() { return 512; } // MB
      public function timeout() { return 30; } // seconds
      
  2. Deployment Strategies:

    • Incremental Updates: Deploy only changed functions:
      php artisan sidecar:deploy --only=ExampleFunction
      
    • Warm Functions: Pre-warm Lambdas on deploy:
      php artisan sidecar:deploy --pre-warm
      
    • Environment Isolation: Use sidecar.env in .env to avoid conflicts in shared AWS accounts.
  3. Execution Patterns:

    • Synchronous Calls:
      $result = ExampleFunction::execute(['input' => 'data']);
      
    • Asynchronous Invocation:
      ExampleFunction::invokeAsync(['input' => 'data']);
      
    • Event-Driven: Trigger via S3/SQS (requires manual AWS setup):
      public function invoke() { return 's3:bucket-name'; }
      
  4. Package Management:

    • Exclude Files:
      public function package() {
          return ['src']->exclude('temp');
      }
      
    • Include Strings as Files:
      $package = new Package(['src']);
      $package->includeString('config.json', json_encode(['key' => 'value']));
      

Integration Tips

  • Laravel Services: Bind functions to the container for dependency injection:
    $this->app->singleton(ExampleFunction::class);
    
  • Testing: Use SidecarTestCase for mocking Lambda responses:
    use Hammerstone\Sidecar\Testing\SidecarTestCase;
    
    public function testFunction() {
        $this->mockLambda(ExampleFunction::class, ['output' => 'test']);
        $result = ExampleFunction::execute([]);
        $this->assertEquals('test', $result['output']);
    }
    
  • CI/CD: Deploy functions in pipelines using:
    php artisan sidecar:deploy --activate --no-interaction
    

Gotchas and Tips

Pitfalls

  1. Runtime Mismatches:

    • Default runtime changed from Node 14 → Node 20 (v0.6.0). Explicitly set runtime if using older versions:
      public function runtime() { return Node::V14; }
      
    • Deprecated runtimes (e.g., .NET 7, Node 16) will fail silently; update to supported versions.
  2. Function Naming:

    • Breaking change in v0.4.0: Long prefixes/names may alter AWS Lambda function names.
    • Use sidecar:name to customize:
      public function name() { return 'custom-name'; }
      
  3. Package Paths:

    • Windows Paths: Use forward slashes (/) or DIRECTORY_SEPARATOR:
      return ['resources/lambda' . DIRECTORY_SEPARATOR . 'handler.js'];
      
    • Relative Paths: Always use absolute paths (e.g., base_path('resources/lambda')).
  4. Cold Starts:

    • Lambdas may have latency on first invocation. Use --pre-warm or set reservedConcurrentExecutions:
      public function concurrency() { return 1; }
      
  5. Environment Variables:

    • Changes require a new deployment to take effect. Use checksums to avoid unnecessary updates:
      public function environment() {
          return ['CHECKSUM' => md5(filemtime('config.json'))];
      }
      
  6. Permissions:

    • Ensure IAM role has:
      • lambda:CreateFunction, lambda:UpdateFunction, lambda:InvokeFunction.
      • iam:PassRole for execution role.
    • Avoid over-permissive roles (e.g., ses, sqs were removed in v0.3.6).

Debugging Tips

  • Logs: Check AWS CloudWatch for Lambda logs or use:

    $result = ExampleFunction::execute(['debug' => true]);
    
  • Errors:

    • 409 Conflict: Function still updating. Wait or use waitUntilFunctionUpdated():
      ExampleFunction::waitUntilFunctionUpdated();
      
    • 429 Throttling: Increase concurrency limits in AWS or retry with exponential backoff.
  • Local Testing:

    • Use sidecar:test to simulate Lambda locally (requires Docker):
      php artisan sidecar:test ExampleFunction
      

Extension Points

  1. Custom Handlers:

    • Override LambdaFunction::execute() to add pre/post-processing:
      public static function execute(array $payload) {
          $payload['meta'] = ['timestamp' => now()];
          return parent::execute($payload);
      }
      
  2. Package Macros:

    • Extend Package class for custom file handling:
      \Hammerstone\Sidecar\Package::macro('includeAssets', function () {
          return $this->include(base_path('public/assets'));
      });
      
  3. Event Listeners:

    • Hook into deployment lifecycle via sidecar.deploying event:
      Event::listen('sidecar.deploying', function ($function) {
          if ($function instanceof ExampleFunction) {
              $function->addEnvironment(['CUSTOM' => 'value']);
          }
      });
      
  4. Container Images:

    • Use Docker images for complex dependencies:
      public function image() { return '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-image:latest'; }
      

Performance Optimizations

  • Ephemeral Storage: Increase for large files:
    public function ephemeralStorage() { return 1024; } // MB
    
  • Concurrency: Limit concurrent executions to avoid throttling:
    public function concurrency() { return 10; }
    
  • Caching: Cache frequent Lambda responses in Laravel’s cache:
    $cacheKey = 'lambda:example:' . md5(json_encode($payload));
    return Cache::remember($cacheKey, now()->addMinutes(5), function () use ($payload) {
        return ExampleFunction::execute($payload);
    });
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi