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.
Installation:
composer require nucleos/matomo-bundle:^4.4.0
Enable the bundle in config/bundles.php:
return [
// ...
Nucleos\MatomoBundle\NucleosMatomoBundle::class => ['all' => true],
];
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%'
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');
}
}
Twig Integration:
Use the matomo_tracker Twig function to track events:
{{ matomo_tracker.trackEvent('Category', 'Action', 'Name') }}
Page Tracking: Automatically track page views in controllers or event listeners:
$tracker->trackPageView($request->getPathInfo());
Event Tracking: Track user interactions (e.g., button clicks, form submissions):
$tracker->trackEvent('Ecommerce', 'Purchase', 'Product ' ~ $productId);
Custom Dimensions: Pass custom dimensions for advanced segmentation:
$tracker->setCustomDimension(1, 'User Role', $user->getRole());
$tracker->trackPageView('/dashboard');
Asynchronous Tracking:
Use the MatomoAsyncTracker service for non-blocking tracking:
$asyncTracker->trackPageView('/async-page');
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');
// ...
}
Token Validation:
tracker_token is correctly set in config. Invalid tokens will silently fail.debug: true in config to log tracking errors.Async Tracking Quirks:
MatomoAsyncTracker uses a queue (default: matomo_async_tracker.queue). Ensure the queue is processed:
php bin/console nucleos:matomo:async:process
Custom Dimensions:
setCustomDimension only for existing IDs.HTTPS/HTTP Mismatch:
tracker_url matches your Matomo instance’s protocol (e.g., https:// for production).Caching:
Settings > General > Disable caching).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();
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']
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());
}
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'
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);
Symfony 8 Compatibility:
composer.json includes compatible constraints:
"require": {
"symfony/*": "^8.0",
"phpunit/phpunit": "^13.0",
"symfony/phpunit-bridge": "^8.0",
"globals": "^16.0"
}
Frontend Dependency Updates:
php bin/console assets:install
npm run build
PHPUnit 13 Migration:
$this->assertTrue($tracker->trackPageView('/test'));
assertEquals() with PHPUnit 13’s updated syntax if applicable.Dependency Updates:
symfony/phpunit-bridge:^8.0 and globals:^16.0. Update your composer.json accordingly.composer update to ensure all dependencies are aligned with the new constraints.New: Frontend Dependency Updates:
package.json and build scripts are updated to handle the new frontend dependencies:
npm install
npm audit fix
Symfony 8 Asset Management:
assets.json manifest is regenerated after updating dependencies:
php bin/console assets:compile
How can I help you explore Laravel packages today?