Skip to content

Plugin API#

Create a class in your module at src/Plugin/Analytic/ and give it the Drupal\analytic\Attribute\Analytic attribute.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use Drupal\analytic\Attribute\Analytic;
use Drupal\analytic\Period;
use Drupal\analytic\Plugin\Analytic\DatabaseAnalyticBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;

#[Analytic(
  id: 'example_total',
  label: new TranslatableMarkup('Example total'),
  description: new TranslatableMarkup('Counts rows this module owns.'),
  dependencies: [],
  modules: [],
)]
final class ExampleTotal extends DatabaseAnalyticBase {

  public function calculate(Period $period): ?float {
    $query = $this->database->select('example_table', 't');
    $query->addExpression('COUNT(*)');
    return (float) $query->execute()->fetchField();
  }

}

calculate() receives the day being stored. A snapshot can ignore the date and measure now. Return NULL to skip the sample. Week, month, and year are not passed to calculate().

Override aggregation() and return AnalyticInterface::AGGREGATION_SUM when a closed week, month, or year should be the total of stored day rows. The runner stores that total only when every day in the window has a row. The default, snapshot, copies the day row on the period end date.

dependencies is a list of other analytic plugin ids. For the same day, those collectors are stored first. The plugin definition exposes that list as requires, because Drupal's attribute base class already uses the name dependencies for PHP class names. modules hides the plugin until each listed module is installed.

Do not write a plugin that queries node_field_data or users_field_data inside this module. If the metric is "published entities," enable the derived published:{entity_type} plugin. If the metric belongs to your module, query your own tables.

Ship an optional config entity to enable the plugin:

1
2
3
4
id: example_total
label: 'Example total'
plugin: example_total
status: true

The file name is analytic.collector.example_total.yml. The id stored in the sample table is example_total.