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

Apihistogram Laravel Package

arnulfosolis/apihistogram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel (Symfony Bundle)

Since this is a Symfony bundle, Laravel integration requires Bridge or manual adaptation. For a quick test:

  1. Install via Composer (adjust for Laravel):

    composer require arnulfosolis/apihistogram @dev
    

    Note: Laravel 5.5+ uses auto-discovery; older versions may need manual registration.

  2. Publish Config (Symfony-style):

    php artisan vendor:publish --provider="ApiHistogram\ApiHistogramBundle\ApiHistogramBundle"
    

    Check config/apihistogram.php for Laravel-compatible config.

  3. Define API Targets in config/apihistogram.php:

    'sites' => [
        'weather_api' => [
            'url' => 'https://api.weather.com/v1/forecast',
            'method' => 'GET',
            'frequency' => 3600, // Update every hour (seconds)
        ],
    ],
    
  4. Run the Command (Symfony CLI):

    php artisan apihistogram:update
    

    For Laravel, create a custom Artisan command to wrap the Symfony command.


First Use Case: Logging API Responses

  1. Configure a target (e.g., public weather API).
  2. Trigger updates via cron or Laravel scheduler:
    // app/Console/Kernel.php
    protected function schedule(Schedule $schedule) {
        $schedule->command('apihistogram:update')->hourly();
    }
    
  3. Query historical data via Eloquent (assuming Doctrine ORM is bridged):
    $histories = ApiHistogram\ApiHistogramBundle\Entity\ApiHistogram::all();
    

Implementation Patterns

Workflow: Asynchronous API Logging

  1. Define Targets in config/apihistogram.php:

    'sites' => [
        'github_trending' => [
            'url' => 'https://api.github.com/search/repositories?q=laravel',
            'method' => 'GET',
            'headers' => ['Authorization' => 'token YOUR_TOKEN'],
            'frequency' => 86400, // Daily
        ],
    ],
    
  2. Extend for Laravel:

    • Create a service provider to register the bundle:
      // app/Providers/ApiHistogramServiceProvider.php
      public function boot() {
          $this->app->register(\ApiHistogram\ApiHistogramBundle\ApiHistogramBundle::class);
      }
      
    • Register the provider in config/app.php.
  3. Customize Storage:

    • Override the Doctrine entity (ApiHistogram\Entity\ApiHistogram) to add Laravel-specific fields (e.g., created_at timestamp).
  4. Integrate with Events:

    // Listen to API response events (if bundle supports hooks)
    Event::listen('apihistogram.response', function ($response, $target) {
        Log::info("Stored response for {$target['url']}", ['response' => $response]);
    });
    

Performance Patterns

  • Batch Updates: Use Laravel’s queue system to process multiple API calls asynchronously:

    // app/Console/Commands/UpdateApiHistograms.php
    public function handle() {
        foreach (config('apihistogram.sites') as $target) {
            UpdateApiHistogramJob::dispatch($target);
        }
    }
    
  • Rate Limiting: Implement middleware to throttle API calls:

    // app/Http/Middleware/ThrottleApiCalls.php
    public function handle($request, Closure $next) {
        $key = $request->ip().'|'.$request->path();
        if (cache()->has($key)) {
            return response('Rate limit exceeded', 429);
        }
        cache()->put($key, true, now()->addSeconds(60));
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Mismatch:

    • The bundle targets Symfony 2.7 and Doctrine ORM v2.4. Laravel’s Eloquent is incompatible. Solution: Use a Doctrine bridge (e.g., laravel-doctrine/orm) or fork the bundle to replace Doctrine with Eloquent.
  2. Asynchronous Quirks:

    • The bundle uses non-blocking HTTP calls, but Laravel’s queue system may introduce delays. Tip: Use sync queues for testing:
      php artisan queue:work --once --env=local
      
  3. Config Overrides:

    • Laravel’s config/caching may ignore published bundle configs. Fix: Manually merge configs in bootstrap/app.php:
      $app->configure('apihistogram');
      
  4. Database Schema:

    • The bundle assumes a single Doctrine schema. Workaround: Use Laravel migrations to extend the api_histograms table:
      Schema::table('api_histograms', function (Blueprint $table) {
          $table->timestamps();
      });
      

Debugging Tips

  1. Command Output:

    • Enable verbose mode for the Symfony command:
      php artisan apihistogram:update --verbose
      
  2. HTTP Errors:

    • Check Guzzle’s default error handling. Debug:
      // Override the HTTP client in the bundle’s service config
      'guzzle' => [
          'timeout' => 30,
          'debug' => true, // Enable debug logs
      ],
      
  3. Database Conflicts:

    • If using Laravel’s created_at, ensure the bundle’s entity doesn’t override it. Solution: Extend the entity and add:
      use Illuminate\Database\Eloquent\Concerns\HasTimestamps;
      

Extension Points

  1. Custom Response Processing:

    • Override the ApiHistogram\ApiHistogramBundle\Service\ApiHistogramService to transform responses before storage:
      // app/Services/CustomApiHistogramService.php
      public function processResponse($response, $target) {
          $data = json_decode($response->getBody(), true);
          return collect($data)->only(['relevant', 'fields']);
      }
      
  2. Webhook Triggers:

    • Replace the cron-based update with Laravel events:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'api.requested' => [CustomApiLogger::class, 'logResponse'],
      ];
      
  3. Multi-Tenant Support:

    • Add a tenant_id field to the histogram table and scope queries:
      // ApiHistogramBundle/Entity/ApiHistogram.php
      public function scopeForTenant($query, $tenantId) {
          return $query->where('tenant_id', $tenantId);
      }
      
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