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.)
Enable the Bundle
Add to config/bundles.php (Symfony 4.4+):
return [
// ...
Webfactory\Bundle\PiwikBundle\WebfactoryPiwikBundle::class => ['all' => true],
];
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)
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.
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 %}
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')
}) }}
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');
}
Event-Based Tracking Trigger custom events (e.g., form submissions) via JavaScript:
_paq.push(['trackEvent', 'Category', 'Action', 'Name', 'Value']);
// src/Twig/AppExtension.php
public function getFunctions() {
return [
new \Twig\TwigFunction('custom_piwik_event', [$this, 'trackCustomEvent']),
];
}
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');
}
{{ piwik_code({ 'async': true }) }}
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.
Missing tracker_url
The config requires tracker_url (no default). Omitting it throws a ParameterNotFoundException at runtime.
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.
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' }) }}
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.
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:
matomo.js: Verify tracker_url is correct and accessible.config/global.php in Matomo).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'
}
}) }}
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
Plugin Integration Use Matomo’s JavaScript API to extend functionality:
{{ piwik_code({
'plugins': ['Heatmap', 'CustomVariables'],
'custom_variables': [{'id': '1', 'name': 'campaign', 'value': 'newsletter'}]
}) }}
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));
How can I help you explore Laravel packages today?