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

Piwik Bundle Laravel Package

devhelp/piwik-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:
    composer require devhelp/piwik-bundle
    
  2. Register the Bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):
    Devhelp\PiwikBundle\DevhelpPiwikBundle::class => ['all' => true],
    
  3. Configure Piwik API in config/packages/devhelp_piwik.yaml:
    devhelp_piwik:
        client: my_piwik.client
        api:
            reader:
                url: "http://your-piwik-instance.com"
                default_params:
                    token_auth: "%env(PIWIK_TOKEN_AUTH)%"
    
  4. Define a Service for a Piwik API method (e.g., getVisitsSummary):
    # config/services.yaml
    services:
        my_piwik.client:
            class: Devhelp\PiwikBundle\Client\Reader
            arguments:
                - "@devhelp_piwik.client"
                - "getVisitsSummary"
    

First Use Case

Inject the service into a controller or command to fetch Piwik data:

use Devhelp\PiwikBundle\Client\ReaderInterface;

class AnalyticsController extends AbstractController
{
    public function showStats(ReaderInterface $piwikReader)
    {
        $result = $piwikReader->call([
            'idSite' => 1,
            'period' => 'day',
            'date' => 'today',
        ]);
        // Process $result (e.g., render as JSON)
    }
}

Implementation Patterns

Common Workflows

  1. Service-Based API Calls: Define reusable services for frequent Piwik API methods (e.g., getVisitsSummary, getActions, getReferrers). Example:

    # config/services.yaml
    services:
        my_piwik.visits_service:
            class: Devhelp\PiwikBundle\Client\Reader
            arguments:
                - "@devhelp_piwik.client"
                - "getVisitsSummary"
    
  2. Dependency Injection: Inject ReaderInterface or WriterInterface (for write operations) into controllers, commands, or services. Example:

    public function __construct(
        private ReaderInterface $piwikReader,
        private WriterInterface $piwikWriter
    ) {}
    
  3. Environment Variables: Store sensitive data (e.g., token_auth) in .env:

    PIWIK_TOKEN_AUTH=your_token_here
    

    Reference it in config/packages/devhelp_piwik.yaml:

    default_params:
        token_auth: "%env(PIWIK_TOKEN_AUTH)%"
    
  4. Batch Processing: Use the call() method to fetch large datasets and process them in chunks:

    $result = $piwikReader->call([
        'idSite' => 1,
        'period' => 'month',
        'format' => 'JSON',
        'token_auth' => $token,
    ]);
    foreach ($result['rows'] as $row) {
        // Process each row
    }
    
  5. Custom Clients: Extend the base Reader or Writer classes to add domain-specific logic:

    class CustomPiwikReader extends Reader
    {
        public function getCustomReport()
        {
            return $this->call([
                'method' => 'API.getCustomReport',
                'idSite' => 1,
                'columns' => 'nb_visits,nb_actions',
                'date' => 'last7',
            ]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Token Authentication:

    • Ensure token_auth is correctly set in default_params or passed per call.
    • Missing or invalid tokens will return HTTP 403 errors. Debug with:
      try {
          $result = $piwikReader->call([...]);
      } catch (\RuntimeException $e) {
          // Log or handle the error (e.g., invalid token)
      }
      
  2. API Rate Limits:

    • Piwik may throttle requests. Implement retries with exponential backoff:
      use Symfony\Component\HttpKernel\Exception\HttpException;
      use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
      
      try {
          $result = $piwikReader->call([...]);
      } catch (ClientExceptionInterface $e) {
          if ($e->getResponse()->getStatusCode() === 429) {
              sleep(2); // Wait before retrying
              return $this->call($params);
          }
          throw $e;
      }
      
  3. Deprecated Methods:

    • Some Piwik API methods may be deprecated. Check the Piwik API docs for alternatives.
    • Example: API.get is deprecated; use API.getVisitsSummary instead.
  4. Configuration Overrides:

    • Avoid hardcoding URLs or tokens in services. Use Symfony’s parameter bag or environment variables.
  5. Caching Responses:

    • Piwik API responses can be cached to reduce load. Use Symfony’s cache system:
      use Symfony\Contracts\Cache\CacheInterface;
      
      public function __construct(
          private ReaderInterface $piwikReader,
          private CacheInterface $cache
      ) {}
      
      public function getCachedData(array $params, string $cacheKey, int $ttl = 3600)
      {
          return $this->cache->get($cacheKey, function () use ($params) {
              return $this->piwikReader->call($params);
          }, $ttl);
      }
      

Debugging Tips

  1. Enable Debug Mode: Set devhelp_piwik.debug: true in config to log raw API responses:

    devhelp_piwik:
        debug: true
    
  2. Validate Parameters: Use the Piwik API docs to validate required parameters for each method. Example:

    // Invalid: Missing 'idSite'
    $piwikReader->call(['period' => 'day']);
    
    // Valid
    $piwikReader->call(['idSite' => 1, 'period' => 'day']);
    
  3. Check HTTP Status Codes: Wrap calls in a try-catch to handle errors gracefully:

    try {
        $result = $piwikReader->call([...]);
    } catch (HttpException $e) {
        $statusCode = $e->getStatusCode();
        $response = $e->getResponse()->getContent();
        // Log or notify (e.g., Slack/email)
    }
    

Extension Points

  1. Custom Response Handlers: Extend the bundle to transform raw Piwik responses into domain objects:

    class PiwikResponseHandler
    {
        public function handle(array $rawData): array
        {
            return array_map(function ($row) {
                return new VisitSummary(
                    $row['nb_visits'],
                    $row['max_actions'],
                    // ...
                );
            }, $rawData['rows']);
        }
    }
    
  2. Event Listeners: Listen to Piwik API events (e.g., after a successful call) to trigger side effects:

    use Devhelp\PiwikBundle\Event\PiwikEvent;
    
    public function onPiwikCall(PiwikEvent $event)
    {
        if ($event->getMethod() === 'API.getVisitsSummary') {
            // Log or process the result
        }
    }
    
  3. Multi-Site Configuration: Support multiple Piwik instances by defining separate clients:

    devhelp_piwik:
        clients:
            main:
                url: "http://main.piwik.pro"
                token: "%env(PIWIK_MAIN_TOKEN)%"
            staging:
                url: "http://staging.piwik.pro"
                token: "%env(PIWIK_STAGING_TOKEN)%"
    

    Then inject the specific client service.

  4. Async Processing: Use Symfony Messenger to process Piwik data asynchronously:

    $message = new FetchPiwikDataMessage($params);
    $this->messageBus->dispatch($message);
    

    Define a handler to call the Piwik API and store results in a database.

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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver