Creating your own statistics
The mechanism behind the displaying of statistics relies on tagged services which are supported since Symfony 4.3
Create your own statistic block
Basic Example
App\Dashboard\Statistics\ArticleStatistic.php
<?php
declare(strict_types=1);
namespace App\Dashboard\Statistics;
use App\Repository\ArticleRepository;
use Monofony\Component\Admin\Dashboard\Statistics\StatisticInterface;
use Symfony\Component\Templating\EngineInterface;
final class ArticleStatistic implements StatisticInterface
{
private $articleRepository;
private $engine;
public function __construct(ArticleRepository $articleRepository, EngineInterface $engine)
{
$this->articleRepository = $articleRepository;
$this->engine = $engine;
}
public function generate(): string
{
$amountOfArticles = $this->articleRepository->countArticles();
return $this->engine->render('backend/dashboard/statistics/_amount_of_articles.html.twig', [
'amountOfArticles' => $amountOfArticles,
]);
}
}
This services needs to implement the App\Dashboard\Statistics\StatisticInterface
.
This way it will be automatically tagged with app.dashboard_statistic
which is used to fetch all existing statistics.
It also enforces you to implement a function called generate()
which need to return a string.
Order your statistics
Since Symfony 4.4 it is possible to sort your services with a static function called getDefaultPriority
.
Here you need to return an integer to set the weight of the service. Statistics with a higher priority will be displayed first.
This is why we chose to work with negative values. (-1 for the first element, -2 for the second,...).
But feel free to use your own sequence when adding more statistics.
public static function getDefaultPriority(): int
{
return -1;
}
Add custom logic to your statistic
Because all statistics are services it's perfectly possible to do anything with them as long as the generate function returns a string. So you can inject any service you want trough Dependency Injection to build your statistic.