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

Matomo Bundle Laravel Package

core23/matomo-bundle

Symfony bundle that wraps Matomo (Piwik) analytics for Sonata projects. Provides services and Twig helpers to render tracking code and access Matomo statistics via a configurable HTTP client (HTTPlug/Symfony HttpClient) and PSR-7 message factory.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nucleos/matomo-bundle:^4.4.0
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Nucleos\MatomoBundle\NucleosMatomoBundle::class => ['all' => true],
    ];
    
  2. Configuration: Add Matomo tracking details to config/packages/nucleos_matomo.yaml:

    nucleos_matomo:
        tracker_url: 'https://your-matomo-instance.com/matomo.php'
        site_id: 1
        tracker_token: 'YOUR_TRACKER_TOKEN'
        debug: '%kernel.debug%'
    
  3. First Use Case (Symfony 8 Compatible): Inject the MatomoTracker service in a controller or Twig template:

    use Nucleos\MatomoBundle\Service\MatomoTracker;
    
    class HomeController extends AbstractController
    {
        public function index(MatomoTracker $tracker): Response
        {
            $tracker->trackPageView('/home');
            return $this->render('home/index.html.twig');
        }
    }
    
  4. Twig Integration: Use the matomo_tracker Twig function to track events:

    {{ matomo_tracker.trackEvent('Category', 'Action', 'Name') }}
    

Implementation Patterns

Common Workflows

  1. Page Tracking: Automatically track page views in controllers or event listeners:

    $tracker->trackPageView($request->getPathInfo());
    
  2. Event Tracking: Track user interactions (e.g., button clicks, form submissions):

    $tracker->trackEvent('Ecommerce', 'Purchase', 'Product ' ~ $productId);
    
  3. Custom Dimensions: Pass custom dimensions for advanced segmentation:

    $tracker->setCustomDimension(1, 'User Role', $user->getRole());
    $tracker->trackPageView('/dashboard');
    
  4. Asynchronous Tracking: Use the MatomoAsyncTracker service for non-blocking tracking:

    $asyncTracker->trackPageView('/async-page');
    

Integration Tips

  • Symfony 8 Events: Subscribe to kernel.request to track all page views automatically:

    public function onKernelRequest(GetResponseEvent $event)
    {
        $tracker->trackPageView($event->getRequest()->getPathInfo());
    }
    
  • Sonata Admin: Extend SonataAdminBundle controllers to track admin actions:

    $tracker->trackEvent('Admin', 'List', 'User List');
    
  • Twig Globals: Expose the tracker globally in Twig for frontend tracking:

    # config/packages/twig.yaml
    twig:
        globals:
            matomo_tracker: '@nucleos_matomo.tracker'
    
  • API Tracking: Track API endpoints by extending AbstractController:

    public function apiAction(Request $request): JsonResponse
    {
        $tracker->trackPageView('/api/endpoint');
        // ...
    }
    

Gotchas and Tips

Common Pitfalls

  1. Token Validation:

    • Ensure tracker_token is correctly set in config. Invalid tokens will silently fail.
    • Debug with debug: true in config to log tracking errors.
  2. Async Tracking Quirks:

    • MatomoAsyncTracker uses a queue (default: matomo_async_tracker.queue). Ensure the queue is processed:
      php bin/console nucleos:matomo:async:process
      
    • Async tracking may not be immediate; verify with Matomo logs.
  3. Custom Dimensions:

    • Dimensions must be pre-configured in Matomo. Use setCustomDimension only for existing IDs.
    • Example config in Matomo: Settings > Custom Dimensions.
  4. HTTPS/HTTP Mismatch:

    • Ensure tracker_url matches your Matomo instance’s protocol (e.g., https:// for production).
  5. Caching:

    • Disable caching for tracking endpoints in Matomo (Settings > General > Disable caching).

Debugging Tips

  • Enable Debug Mode:

    nucleos_matomo:
        debug: true
    

    Logs will appear in Symfony’s debug toolbar or var/log/dev.log.

  • Check Network Requests: Use browser dev tools to verify tracking pixels are loaded:

    https://your-matomo-instance.com/matomo.php?idsite=1&rec=1&...
    
  • Matomo Logs: Inspect Matomo’s log_visit table for missing visits:

    SELECT * FROM log_visit WHERE idsite = 1 AND period = NOW();
    

Extension Points

  1. Custom Tracker Services: Extend MatomoTracker to add domain-specific methods:

    class CustomMatomoTracker extends MatomoTracker
    {
        public function trackUserLogin(User $user)
        {
            $this->trackEvent('Auth', 'Login', $user->getEmail());
        }
    }
    

    Register as a service:

    services:
        app.matomo.tracker:
            class: App\Service\CustomMatomoTracker
            arguments: ['@nucleos_matomo.tracker']
    
  2. Event Listeners: Create listeners for automatic tracking (e.g., on kernel.terminate):

    public static function getSubscribedEvents()
    {
        return [
            'kernel.terminate' => 'trackTerminate',
        ];
    }
    
    public function trackTerminate(Request $request, Response $response)
    {
        $tracker->trackPageView($request->getPathInfo());
    }
    
  3. Configuration Overrides: Override bundle config dynamically (e.g., per-environment):

    # config/packages/dev/nucleos_matomo.yaml
    nucleos_matomo:
        debug: true
        tracker_url: 'http://matomo.dev/matomo.php'
    
  4. Testing (PHPUnit 13 Compatible): Mock MatomoTracker in PHPUnit 13:

    $mockTracker = $this->createMock(MatomoTracker::class);
    $mockTracker->expects($this->once())->method('trackPageView');
    $this->container->set('nucleos_matomo.tracker', $mockTracker);
    
  5. Symfony 8 Compatibility:

    • The bundle now officially supports Symfony 8. Ensure your composer.json includes compatible constraints:
      "require": {
          "symfony/*": "^8.0",
          "phpunit/phpunit": "^13.0",
          "symfony/phpunit-bridge": "^8.0",
          "globals": "^16.0"
      }
      
    • Verify all dependencies are updated to their latest Symfony 8-compatible versions.
  6. Frontend Dependency Updates:

    • The release updates frontend dependencies (e.g., JavaScript/CSS assets). Clear your cache and rebuild assets if needed:
      php bin/console assets:install
      npm run build
      
    • Ensure your frontend build tooling (e.g., Webpack Encore) is configured to handle the updated dependencies.
  7. PHPUnit 13 Migration:

    • Update your test suite to use PHPUnit 13 assertions and syntax. For example:
      $this->assertTrue($tracker->trackPageView('/test'));
      
    • Replace deprecated methods like assertEquals() with PHPUnit 13’s updated syntax if applicable.
  8. Dependency Updates:

    • The bundle now requires symfony/phpunit-bridge:^8.0 and globals:^16.0. Update your composer.json accordingly.
    • Run composer update to ensure all dependencies are aligned with the new constraints.
  9. New: Frontend Dependency Updates:

    • The release includes updated frontend dependencies. If you rely on custom JavaScript/CSS integrations, verify compatibility with the new versions.
    • Check for breaking changes in the updated frontend libraries (e.g., jQuery, Bootstrap) and update your custom scripts if necessary.
    • Ensure your package.json and build scripts are updated to handle the new frontend dependencies:
      npm install
      npm audit fix
      
  10. Symfony 8 Asset Management:

    • If using Symfony’s asset management system, ensure your assets.json manifest is regenerated after updating dependencies:
      php bin/console assets:compile
      
    • Verify that all frontend assets (e.g., Matomo JavaScript tracker) are correctly loaded in your templates.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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