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

Drom Laravel Package

baks-dev/drom

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baks-dev/drom
    

    Ensure your project meets the PHP 8.4+ requirement and has baks-dev/core (≥7.4) installed.

  2. Service Provider Registration Add the provider to config/app.php under providers:

    BaksDev\Drom\DromServiceProvider::class,
    
  3. Publish Configuration (if needed) Run:

    php artisan vendor:publish --provider="BaksDev\Drom\DromServiceProvider" --tag="config"
    

    Check config/drom.php for default settings.

  4. First Use Case: Basic API Integration Use the facade to interact with DROM APIs (e.g., fetching data):

    use BaksDev\Drom\Facades\Drom;
    
    $response = Drom::get('/api/endpoint');
    $data = $response->json();
    

Implementation Patterns

Core Workflows

  1. API Requests

    • Facade-based calls (recommended for simplicity):
      $response = Drom::post('/api/users', ['name' => 'John']);
      
    • Custom HTTP Client (for advanced use):
      $client = Drom::client()->withHeaders(['Authorization' => 'Bearer token']);
      $response = $client->get('/api/data');
      
  2. Middleware Integration Attach middleware to all DROM requests via config (config/drom.php):

    'middleware' => [
        \BaksDev\Drom\Middleware\AuthMiddleware::class,
        \BaksDev\Drom\Middleware\LoggingMiddleware::class,
    ],
    
  3. Event Handling Subscribe to DROM events (e.g., DromRequesting, DromResponded) in an EventServiceProvider:

    protected $listen = [
        'BaksDev\Drom\Events\DromRequesting' => [
            \App\Listeners\LogDromRequest::class,
        ],
    ];
    
  4. Response Transformation Use the transform() method to normalize responses:

    $transformed = Drom::get('/api/items')->transform(function ($data) {
        return collect($data)->map(fn ($item) => [
            'id' => $item['id'],
            'name' => strtoupper($item['name']),
        ]);
    });
    
  5. Queueing Long-Running Requests Dispatch jobs for async processing:

    use BaksDev\Drom\Jobs\DromApiJob;
    
    DromApiJob::dispatch('GET', '/api/heavy-task', ['param' => 'value']);
    

Integration Tips

  • Laravel HTTP Client Compatibility Leverage Laravel’s built-in HTTP client features (e.g., throwIf(), retry()) with DROM’s client:

    $response = Drom::client()->throwIf($status !== 200)->get('/api/data');
    
  • Caching Responses Cache API responses using Laravel’s cache system:

    $data = Cache::remember('drom_api_data', now()->addHours(1), function () {
        return Drom::get('/api/data')->json();
    });
    
  • Testing Mock DROM calls in tests using the Drom facade:

    $this->mock(Drom::class)->shouldReceive('get')->andReturn(response()->json(['test' => true]));
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch

    • Issue: Package requires PHP 8.4+. Using an older version will fail silently or throw cryptic errors.
    • Fix: Update PHP or check the composer.json require section for compatibility.
  2. Missing Core Dependency

    • Issue: baks-dev/core (≥7.4) is a hard dependency. Installing drom without it will cause autoloading errors.
    • Fix: Run composer require baks-dev/core:^7.4 first.
  3. Facade Not Bound

    • Issue: Forgetting to register DromServiceProvider or publish config may lead to ClassNotFound errors.
    • Fix: Verify config/app.php and run php artisan config:clear if needed.
  4. Middleware Conflicts

    • Issue: Custom middleware may interfere with DROM’s default headers (e.g., Accept: application/json).
    • Fix: Exclude DROM routes from conflicting middleware or adjust middleware order.
  5. Rate Limiting

    • Issue: DROM APIs may throttle requests. Default Laravel HTTP client lacks built-in rate limiting.
    • Fix: Use spatie/rate-limiter or implement custom middleware:
      Drom::client()->withMiddleware(new \Spatie\RateLimiter\Limit('api', 60, 60));
      

Debugging

  1. Enable Debug Logging Add to config/drom.php:

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

    Logs will appear in storage/logs/laravel.log.

  2. Inspect Raw Responses Use tap() to debug responses:

    Drom::get('/api/data')->tap(function ($response) {
        \Log::debug('Raw response:', $response->toPsrResponse());
    });
    
  3. Handle Exceptions Wrap DROM calls in try-catch blocks:

    try {
        $response = Drom::get('/api/data');
    } catch (\BaksDev\Drom\Exceptions\DromException $e) {
        \Log::error('DROM API failed:', ['error' => $e->getMessage()]);
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    

Extension Points

  1. Custom HTTP Clients Bind a custom client in the service provider:

    $this->app->singleton(\BaksDev\Drom\Contracts\DromClient::class, function ($app) {
        return new \GuzzleHttp\Client(['base_uri' => 'https://custom-api.com']);
    });
    
  2. Extend Response Handling Create a macro for the Drom facade:

    Drom::macro('customMethod', function ($endpoint) {
        return $this->get($endpoint)->transform(...);
    });
    
  3. Add New Middleware Extend the DromMiddleware class:

    namespace App\Middleware;
    
    use BaksDev\Drom\Middleware\DromMiddleware;
    
    class CustomDromMiddleware extends DromMiddleware {
        public function handle($request, \Closure $next) {
            // Add custom logic
            return parent::handle($request, $next);
        }
    }
    

    Register it in config/drom.php:

    'middleware' => [
        \App\Middleware\CustomDromMiddleware::class,
    ],
    
  4. Override Default Config Publish and modify config/drom.php:

    'timeout' => 30, // Default: 10 seconds
    'base_uri' => env('DROM_API_URL', 'https://api.drom.example'),
    

Pro Tips

  • Use Environment Variables Store API URLs/keys in .env:

    DROM_API_URL=https://api.drom.example
    DROM_API_KEY=your_key_here
    

    Access via config:

    config('drom.base_uri'); // Uses .env value
    
  • Type-Hint DROM Contracts For better IDE support, type-hint interfaces:

    public function __construct(private \BaksDev\Drom\Contracts\DromClient $client) {}
    
  • Leverage Laravel’s Http Facade Combine DROM with Laravel’s HTTP client for hybrid requests:

    $response = \Http::withOptions(['base_uri' => config('drom.base_uri')])->get('/api/data');
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky