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

One Stat Laravel Package

chill-project/one-stat

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require chill-project/one-stat
    

    Publish the config (if available) and migrations:

    php artisan vendor:publish --provider="ChillProject\OneStat\OneStatServiceProvider" --tag="config"
    php artisan vendor:publish --provider="ChillProject\OneStat\OneStatServiceProvider" --tag="migrations"
    

    Run migrations:

    php artisan migrate
    
  2. First Use Case Fetch basic stats for a child (e.g., ID 123):

    use ChillProject\OneStat\Facades\OneStat;
    
    $stats = OneStat::getChildStats(123);
    dd($stats);
    
    • Verify the response structure (e.g., total_visits, last_updated).
    • Check the API docs for endpoint specifics.

Implementation Patterns

Core Workflows

  1. Fetching Stats

    • Child-level stats:
      $stats = OneStat::getChildStats($childId);
      
    • Aggregated stats (e.g., by region):
      $regionStats = OneStat::getRegionStats('BRU'); // Brussels
      
    • Custom queries (if supported):
      $stats = OneStat::query()
          ->where('date', '>=', now()->subDays(7))
          ->get();
      
  2. Caching Responses Cache frequent requests (e.g., dashboard stats) for 5–15 minutes:

    $stats = Cache::remember("one_stat_child_{$childId}", now()->addMinutes(10), function() use ($childId) {
        return OneStat::getChildStats($childId);
    });
    
  3. Event Listeners Trigger actions on stat updates (e.g., notify admins if visits drop):

    // In EventServiceProvider
    protected $listen = [
        \ChillProject\OneStat\Events\StatsUpdated::class => [
            \App\Listeners\AlertLowVisits::class,
        ],
    ];
    
  4. API Integration Expose stats via Laravel API:

    Route::get('/stats/child/{id}', function ($id) {
        return response()->json(OneStat::getChildStats($id));
    });
    

Integration Tips

  • Validation: Validate childId/region inputs before passing to the package.
  • Rate Limiting: Use Laravel’s throttle middleware if the external API has limits.
  • Logging: Log failed requests for debugging:
    try {
        $stats = OneStat::getChildStats($id);
    } catch (\Exception $e) {
        Log::error("ONEStat fetch failed for child {$id}: " . $e->getMessage());
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • The external API may throttle requests. Test with sleep() or queue delayed jobs:
      sleep(1); // Add delay between requests
      
    • Use Laravel queues for batch processing:
      OneStat::dispatchSyncStatsUpdate($childIds)->onQueue('stat-updates');
      
  2. Data Mismatches

    • Ensure childId in your DB matches the external API’s format (e.g., string vs. integer).
    • Handle missing data gracefully:
      $stats = OneStat::getChildStats($id) ?? collect(['visits' => 0]);
      
  3. Time Zones

    • The package may return timestamps in UTC. Normalize with:
      $stats->last_updated = $stats->last_updated->setTimezone('Europe/Brussels');
      
  4. Configuration Quirks

    • Check config/onestat.php for:
      • API base URL (default: https://api.onestat.be).
      • Authentication (if required, e.g., API keys).
    • Override defaults in .env:
      ONESTAT_API_KEY=your_key_here
      

Debugging

  • Enable Debug Mode:
    OneStat::setDebug(true); // Logs API requests/responses
    
  • Mock External API (for testing): Use Laravel’s HTTP client mocking:
    Http::fake([
        'api.onestat.be/*' => Http::response(['visits' => 5], 200),
    ]);
    

Extension Points

  1. Custom Endpoints Extend the package by adding new methods to the facade:

    // In OneStatServiceProvider
    $this->app->extend('onestat', function ($service) {
        $service->addMethod('getCustomStats', function ($id) {
            return $this->callExternalApi("custom/{$id}");
        });
        return $service;
    });
    
  2. Webhooks If the external API supports webhooks, create a Laravel route to handle callbacks:

    Route::post('/onestat/webhook', function (Request $request) {
        OneStat::handleWebhook($request->all());
    });
    
  3. Database Sync Sync local DB with external stats periodically (e.g., via cron):

    * * * * * php artisan onestat:sync
    

    Create a custom Artisan command:

    php artisan make:command SyncOneStat
    
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