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

Anonlytics Lib Php Laravel Package

defixit/anonlytics-lib-php

PHP library for anonymous analytics (Anonlytics). Collect lightweight, privacy-first event data without cookies or personal identifiers, and send it to an Anonlytics server/API from your PHP apps and services.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require defixit/anonlytics-lib-php:^2.0

Add the service provider to config/app.php:

'providers' => [
    Defixit\Anonlytics\AnonlyticsServiceProvider::class,
],
  1. Configuration Publish the config file:

    php artisan vendor:publish --provider="Defixit\Anonlytics\AnonlyticsServiceProvider"
    

    Update config/anonlytics.php with your API key, domain, and ensure PHP 8.3 compatibility.

  2. First Use Case Track a page view in a Laravel controller:

    use Defixit\Anonlytics\Facades\Anonlytics;
    
    public function show()
    {
        Anonlytics::pageView('/dashboard');
        return view('dashboard');
    }
    

Implementation Patterns

Core Workflows

  1. Event Tracking

    // Track custom events with properties (PHP 8.3 type safety)
    Anonlytics::track('user_signed_up', [
        'email' => auth()->user()->email,
        'plan' => auth()->user()->plan,
    ]);
    
  2. User Identification

    // Identify a user (e.g., after login)
    Anonlytics::identify(auth()->user()->id, [
        'name' => auth()->user()->name,
        'email' => auth()->user()->email,
    ]);
    
  3. E-Commerce Tracking

    // Track purchases with improved error handling
    Anonlytics::track('purchase', [
        'revenue' => $order->total,
        'items' => array_map(fn($item) => [
            'id' => $item->id,
            'price' => $item->price,
            'quantity' => $item->quantity,
        ], $order->items),
    ]);
    

Integration Tips

  • Middleware for Automatic Tracking Create middleware to track page views automatically:

    // app/Http/Middleware/TrackPages.php
    public function handle($request, Closure $next)
    {
        Anonlytics::pageView($request->path());
        return $next($request);
    }
    

    Register in app/Http/Kernel.php:

    'web' => [
        \App\Http\Middleware\TrackPages::class,
        // ...
    ],
    
  • Queue Events for Async Tracking Dispatch events to a queue to avoid blocking requests:

    event(new \Defixit\Anonlytics\Events\TrackEvent('event_name', $properties));
    

    Configure the queue in config/anonlytics.php:

    'queue' => env('ANONLYTICS_QUEUE', 'default'),
    'timeout' => 5, // New: Timeout in seconds for API calls
    
  • Laravel Scout Integration Sync Scout model updates to Anonlytics:

    // In your Scout model observer
    public function saved($model)
    {
        Anonlytics::track('model_updated', [
            'model' => get_class($model),
            'id' => $model->id,
        ]);
    }
    

Gotchas and Tips

Common Pitfalls

  1. PHP 8.3 Compatibility

    • Ensure your project uses PHP 8.3. The package no longer supports PHP 7.4.
    • Update composer.json and server configuration accordingly.
  2. API Key Validation

    • Ensure ANONLYTICS_API_KEY is set in .env; the library now throws a more descriptive exception if missing.
    • Debug with:
      Anonlytics::getConfig(); // Verify keys are loaded
      
  3. Timeouts and Rate Limiting

    • Configure timeout in config/anonlytics.php to prevent hanging requests (default: 5s).
    • Handle rate limits gracefully:
      try {
          Anonlytics::track('event');
      } catch (\Defixit\Anonlytics\Exceptions\RateLimitException $e) {
          sleep($e->retryAfter);
          retry();
      }
      
  4. Sensitive Data

    • Avoid sending PII (e.g., passwords, tokens) in event properties. Use hashes or omit entirely.

Debugging

  • Enable Logging Set debug: true in config/anonlytics.php to log payloads:

    'debug' => env('ANONLYTICS_DEBUG', false),
    
  • Mocking for Tests Use a mock client in tests:

    $this->app->singleton(\Defixit\Anonlytics\Anonlytics::class, function () {
        return new \Defixit\Anonlytics\Anonlytics(new \Defixit\Anonlytics\MockClient());
    });
    
  • New: HTTPS for GeoIP All external API calls (e.g., GeoIP) now use HTTPS by default for security.

Extension Points

  1. Custom Payload Transformers Override the default payload structure:

    // app/Providers/AnonlyticsServiceProvider.php
    public function boot()
    {
        Anonlytics::extend(function ($payload) {
            $payload['custom_field'] = 'value';
            return $payload;
        });
    }
    
  2. Batch Processing For high-volume tracking, implement batching:

    Anonlytics::flush(); // Force-send queued events
    
  3. Webhook Fallback If Anonlytics is down, log events to a fallback (e.g., database):

    Anonlytics::setFallback(function ($event) {
        \App\Models\AnonlyticsEvent::create($event);
    });
    
  4. New: Timeout Configuration Customize API call timeouts in config/anonlytics.php:

    'timeout' => 10, // Increase timeout for slower connections
    
  5. Error Handling Leverage improved exceptions for better debugging:

    try {
        Anonlytics::track('event');
    } catch (\Defixit\Anonlytics\Exceptions\ApiException $e) {
        report($e); // Use Laravel's error reporting
    }
    

NO_UPDATE_NEEDED was not applicable due to breaking changes and new features in 2.0.0.
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.
phpshko/laravel-livewire-depdrop
larasell-dev/larasell
calliostro/spotify-bundle
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer