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

bretrzaun/matomo-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require webfactory/piwik-bundle
    

    (Note: The README mentions webfactory/piwik-bundle, but the repo is bretrzaun/matomo-bundle. Verify the correct package name in your project.)

  2. Enable the Bundle Add to config/bundles.php (Symfony 4.4+):

    return [
        // ...
        Webfactory\Bundle\PiwikBundle\WebfactoryPiwikBundle::class => ['all' => true],
    ];
    
  3. Basic Configuration Add to config/packages/webfactory_piwik.yaml:

    webfactory_piwik:
        site_id: 1  # Replace with your Matomo site ID
        tracker_url: "https://your-matomo-instance.com"  # Required
        enable: true  # Disable in dev (default: true)
    
  4. First Use Case Insert the Twig function just before </body> in your base template (e.g., base.html.twig):

    {{ piwik_code() }}
    

    This auto-generates the Matomo tracking snippet with your configured site_id and tracker_url.


Implementation Patterns

Workflows

  1. Dynamic Tracking Control Disable tracking in dev/staging via environment variables:

    # config/packages/dev/webfactory_piwik.yaml
    webfactory_piwik:
        enable: false
    

    Or dynamically in Twig:

    {% if app.environment === 'prod' %}
        {{ piwik_code() }}
    {% endif %}
    
  2. Custom Tracking Parameters Override default parameters (e.g., url, title) via Twig:

    {{ piwik_code({
        'url': app.request.getUri(),
        'title': app.request.get('page_title', 'Default Title')
    }) }}
    
  3. Multi-Site Tracking Use dependency injection to fetch config per environment:

    // src/Service/MatomoTracker.php
    public function __construct(private ContainerInterface $container) {}
    
    public function getTrackerUrl(): string {
        return $this->container->getParameter('webfactory_piwik.tracker_url');
    }
    
  4. Event-Based Tracking Trigger custom events (e.g., form submissions) via JavaScript:

    _paq.push(['trackEvent', 'Category', 'Action', 'Name', 'Value']);
    

Integration Tips

  • Twig Extensions: Extend the bundle’s Twig environment to add custom filters:
    // src/Twig/AppExtension.php
    public function getFunctions() {
        return [
            new \Twig\TwigFunction('custom_piwik_event', [$this, 'trackCustomEvent']),
        ];
    }
    
  • Symfony Events: Listen to kernel.request to modify tracking data dynamically:
    // src/EventListener/MatomoListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        $request->attributes->set('piwik_custom_dimension', 'user_id_123');
    }
    
  • Asset Optimization: Ensure the tracking script is loaded asynchronously to avoid blocking:
    {{ piwik_code({ 'async': true }) }}
    

Gotchas and Tips

Pitfalls

  1. Bundle Naming Mismatch The README references webfactory/piwik-bundle, but the repo is bretrzaun/matomo-bundle. Verify the correct package name in composer.json to avoid autoloading errors.

  2. Missing tracker_url The config requires tracker_url (no default). Omitting it throws a ParameterNotFoundException at runtime.

  3. Twig Function Scope The piwik_code() function must be called in a template (not a controller). Directly invoking it in PHP (e.g., piwik_code()) will fail.

  4. Caching Issues If using HTTP caching (e.g., Varnish), ensure the tracking script isn’t cached. Add a Cache-Control: no-cache header or use a unique query string:

    {{ piwik_code({ 'cache_buster': 'v1' }) }}
    
  5. SSL Mixed Content If your site uses HTTPS but tracker_url is HTTP, modern browsers may block the tracking script. Use https:// for tracker_url or configure HSTS.

Debugging

  • Check Config Dumping Symfony’s config dumper (php bin/console debug:config webfactory_piwik) confirms loaded parameters.

    php bin/console debug:config webfactory_piwik
    
  • Validate Tracking Code Inspect the generated HTML to ensure the script loads correctly:

    <!-- Expected output -->
    <script type="text/javascript">
        var _paq = window._paq = window._paq || [];
        _paq.push(['trackPageView']);
        _paq.push(['enableLinkTracking']);
        (function() {
            var u="//your-matomo-instance.com/";
            _paq.push(['setTrackerUrl', u+'matomo.php']);
            _paq.push(['setSiteId', '1']);
            var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
            g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
        })();
    </script>
    
  • Network Tab Errors Common issues:

    • 404 on matomo.js: Verify tracker_url is correct and accessible.
    • CORS Errors: Ensure your Matomo instance allows requests from your domain (check config/global.php in Matomo).

Extension Points

  1. Custom Tracking Variables Override the Twig function to inject custom variables:

    {{ piwik_code({
        'custom_dimensions': {
            '1': 'user_segment',  // Matomo custom dimension slot 1
            '2': 'device_type'
        }
    }) }}
    
  2. Dynamic Site ID Fetch site_id from a database or API:

    # config/packages/webfactory_piwik.yaml
    webfactory_piwik:
        site_id: "%env(PIWIK_SITE_ID)%"  # Load from .env
    
  3. Plugin Integration Use Matomo’s JavaScript API to extend functionality:

    {{ piwik_code({
        'plugins': ['Heatmap', 'CustomVariables'],
        'custom_variables': [{'id': '1', 'name': 'campaign', 'value': 'newsletter'}]
    }) }}
    
  4. Symfony Messenger Dispatch tracking events as messages for async processing:

    // src/Message/TrackPageView.php
    class TrackPageView implements MessageInterface {
        public string $pageUrl;
        public string $title;
    }
    
    // Controller
    $bus->dispatch(new TrackPageView($request->getUri(), $title));
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours