Weave 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

Bridge Builder Laravel Package

splash/bridge-builder

Laravel package for building and managing bridges between systems, providing tools to define connections, map data flows, and orchestrate integration logic in a structured, reusable way. Suitable for apps needing reliable cross-service communication and syncing.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Install the Package

    composer require splash/bridge-builder
    

    Verify PHP version (>=8.1) and extensions (curl, posix) are enabled.

  2. Publish Configuration

    php artisan vendor:publish --provider="Splash\BridgeBuilder\BridgeBuilderServiceProvider"
    

    Edit config/bridge-builder.php to define:

    • phar_path: Directory to store generated PHARs (e.g., storage/app/phars).
    • default_worker: Base class for workers (extends Splash\BridgeBuilder\Worker).
  3. Generate a Skeleton Worker

    php artisan bridge:make Worker MyConnectorWorker
    

    This creates:

    • app/Workers/MyConnectorWorker.php (Laravel service class).
    • phar-skeleton/MyConnectorWorker/ (PHAR project structure).
  4. First Use Case: Queue Job Create a Laravel job to trigger the PHAR:

    // app/Jobs/ProcessConnector.php
    use Splash\BridgeBuilder\Facades\BridgeBuilder;
    
    class ProcessConnector implements ShouldQueue {
        public function handle() {
            $result = BridgeBuilder::run('MyConnectorWorker', ['input' => 'data']);
            // Handle $result (e.g., log, return to user)
        }
    }
    

    Dispatch it:

    ProcessConnector::dispatch();
    

Implementation Patterns

1. Worker Development Workflow

A. Laravel Service → PHAR Migration

  1. Extract Logic Move connector logic (e.g., Stripe API calls) into a standalone class:

    // app/Workers/StripePaymentWorker.php
    namespace App\Workers;
    
    use Splash\BridgeBuilder\Worker;
    
    class StripePaymentWorker extends Worker {
        public function handle($input) {
            return \Stripe\Charge::create($input);
        }
    }
    
  2. Generate PHAR

    php artisan bridge:build StripePaymentWorker
    

    Outputs storage/app/phars/stripe-payment-worker.phar.

  3. Trigger from Laravel

    // In a controller or job
    $result = BridgeBuilder::run('stripe-payment-worker', [
        'amount' => 1000,
        'currency' => 'usd',
    ]);
    

B. PHAR as a Queue Worker

Configure Laravel’s queue to execute PHARs:

// config/queue.php
'connections' => [
    'phar' => [
        'driver' => 'bridge',
        'worker' => 'StripePaymentWorker',
        'timeout' => 60,
    ],
],

Dispatch a job:

ProcessPayment::dispatch()->onConnection('phar');

2. Data Flow Patterns

A. Input/Output Handling

  • Structured Input: Pass data as an array or JSON string:
    BridgeBuilder::run('worker', json_encode(['key' => 'value']));
    
  • Output Parsing: PHARs return JSON by default. Parse in Laravel:
    $output = json_decode(BridgeBuilder::run('worker', $input), true);
    

B. Shared Dependencies

  • Laravel Services: Inject via Worker::getContainer():
    // In PHAR worker
    $this->getContainer()->make('App\Services\Logger');
    
  • External APIs: Use Laravel’s HTTP client (configured in PHAR’s bootstrap.php):
    $http = $this->getContainer()->make('Illuminate\Http\Client\PendingRequest');
    $response = $http->get('https://api.example.com')->json();
    

C. Error Handling

  • PHAR Exceptions: Laravel catches and logs them:
    try {
        BridgeBuilder::run('worker', $input);
    } catch (\Splash\BridgeBuilder\Exceptions\WorkerFailed $e) {
        Log::error('Worker failed', ['error' => $e->getOutput()]);
    }
    
  • Custom Errors: Throw JSON-serializable errors in PHAR:
    throw new \RuntimeException(json_encode(['error' => 'Invalid input']));
    

3. Advanced Patterns

A. PHAR with Laravel Facades

Extend PHAR’s bootstrap.php to include Laravel facades:

// phar-skeleton/StripePaymentWorker/bootstrap.php
$container->singleton('App', function () {
    return new \Illuminate\Foundation\Application();
});

Now use facades in the worker:

// In PHAR worker
Log::info('Processing payment...');

B. Dynamic Worker Loading

Load workers dynamically based on config:

// config/bridge-builder.php
'workers' => [
    'stripe' => 'StripePaymentWorker',
    'paypal' => 'PaypalPaymentWorker',
],

Run dynamically:

$workerName = config('bridge-builder.workers.default');
BridgeBuilder::run($workerName, $input);

C. PHAR as a CLI Tool

Generate a PHAR with a CLI entry point:

// In Worker class
public function handle($input) {
    if ($this->isCli()) {
        // CLI-specific logic
    }
    return $this->process($input);
}

Run via:

php storage/app/phars/stripe-payment-worker.phar --input='{"amount":100}'

Gotchas and Tips

Pitfalls

  1. PHAR Execution Permissions

    • Issue: PHARs may fail with phar extension not enabled or Permission denied.
    • Fix: Ensure phar.readonly=0 in php.ini and set executable permissions:
      chmod +x storage/app/phars/*.phar
      
  2. Dependency Conflicts

    • Issue: PHARs may pull different versions of packages than the Laravel app.
    • Fix: Use composer.json in the PHAR project to lock versions:
      {
          "require": {
              "stripe/stripe-php": "^8.0",
              "illuminate/support": "9.0.*"
          }
      }
      
  3. State Management

    • Issue: PHARs are stateless; shared memory (e.g., Laravel cache) may not persist.
    • Fix: Use Redis or database for shared state:
      // In PHAR worker
      $cache = $this->getContainer()->make('Illuminate\Cache\Repository');
      $value = $cache->get('key');
      
  4. Debugging Challenges

    • Issue: No IDE breakpoints; logs may not appear in Laravel’s log files.
    • Fix:
      • Redirect PHAR output to a file:
        // In Worker class
        public function handle($input) {
            file_put_contents(
                storage_path('logs/phar-debug.log'),
                print_r($input, true),
                FILE_APPEND
            );
        }
        
      • Use stderr redirection in bridge:build config.
  5. PHAR Size Limits

    • Issue: PHARs >50MB may fail to execute.
    • Fix: Exclude large dependencies or use Docker for heavy workers.

Debugging Tips

  1. Enable PHAR Debugging Add to config/bridge-builder.php:

    'debug' => env('BRIDGE_DEBUG', false),
    

    This logs PHAR execution details to storage/logs/bridge-builder.log.

  2. Inspect PHAR Contents List files in the PHAR:

    phar -l storage/app/phars/worker.phar
    

    Extract for testing:

    phar -x worker.phar
    
  3. Test Locally Run PHARs directly:

    php storage/app/phars/worker.phar --input='{"test":123}'
    

Extension Points

  1. Custom Worker Classes Extend Splash\BridgeBuilder\Worker to add shared logic:

    namespace App\Workers;
    
    use Splash\BridgeBuilder\Worker;
    
    class BaseWorker extends Worker {
        protected function log($message) {
            $this->getContainer()->make('App\Services\Logger')->info($message);
        }
    }
    
  2. PHAR Pre/Post Hooks Add logic before/after PHAR execution in app/Providers/BridgeBuilderServiceProvider.php:

    public function boot() {
        BridgeBuilder::preRun(function ($worker, $input) {
            Log::debug("Running {$worker} with input: " . json_encode($input));
        });
    
        BridgeBuilder::postRun(function ($worker, $output, $exception) {
            if ($exception) {
                Alert::send("PHAR {$worker
    
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.
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource