Laurent Voullemier
Contributed by Laurent Voullemier in #37332

The Symfony profiler uses data collectors to gather all the debug information that is later displayed in the toolbar and the profiler. These data collectors are services whose classes implement the DataCollectorInterface.

When the data collector includes Twig templates to display its data, you must register the service manually to define the template to use. For example, when using YAML for config:

1
2
3
4
5
6
7
8
# config/services.yaml
services:
    App\DataCollector\MyCustomDataCollector:
        tags:
            -
                name:     data_collector
                template: 'data_collector/template.html.twig'
                id:       'app.my_custom_collector'

In Symfony 5.2 we've simplified the creation of custom data collectors with the introduction of a new AbstractDataCollector class. If you extend this class in your custom collectors, you can optionally define the following methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/DataCollector/MyCustomDataCollector.php
namespace App\DataCollector;

use Symfony\Bundle\FrameworkBundle\DataCollector\AbstractDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;

class MyCustomDataCollector extends AbstractDataCollector
{
    // ...

    public function collect(Request $request, Response $response, \Throwable $exception = null)
    {
        $this->data = '...';
    }

    public static function getTemplate(): ?string
    {
        return 'data_collector/template.html.twig';
    }

    public function getName()
    {
        return 'app.my_custom_collector';
    }
}

That's it! When using the default service configuration with autoconfigure Symfony will register this data collector automatically and will use it starting from the next request. You don't need to register services manually anymore.

The only caveat is that the collector priority can't be configured this way, so you must still register the service manually to set the priority.

Published in #Living on the edge