tourze/counter-bundle

Symfony Counter Bundle

Installs: 16

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:symfony-bundle

0.0.3 2025-04-16 05:44 UTC

This package is auto-updated.

Last update: 2025-04-17 13:33:37 UTC


README

English | 中文

Latest Version Total Downloads

A Symfony bundle that provides a complete entity counting system with features like automatic statistics, manual increment/decrement, and scheduled updates.

Features

  • Automatic entity counting with performance optimization for large tables
  • Manual counter management with increment/decrement support
  • Scheduled counter updates via cron jobs
  • Context-aware counter tracking
  • Easy integration with Symfony's admin interface
  • Support for custom counter providers

Installation

composer require tourze/counter-bundle

Quick Start

  1. Register the bundle in config/bundles.php:
return [
    // ...
    CounterBundle\CounterBundle::class => ['all' => true],
];
  1. Create a custom counter provider:
use CounterBundle\Provider\CounterProvider;
use CounterBundle\Entity\Counter;

#[AutoconfigureTag('app.counter.provider')]
class CustomCounterProvider implements CounterProvider
{
    public function getCounters(): iterable
    {
        yield new Counter('users.total', 'Total Users');
        yield new Counter('orders.total', 'Total Orders');
    }
}
  1. Use the counter in your service:
use CounterBundle\Repository\CounterRepository;

class YourService
{
    public function __construct(
        private readonly CounterRepository $counterRepository
    ) {}

    public function getStatistics(): array
    {
        return [
            'users' => $this->counterRepository->findOneBy(['name' => 'users.total'])?->getCount() ?? 0,
            'orders' => $this->counterRepository->findOneBy(['name' => 'orders.total'])?->getCount() ?? 0,
        ];
    }
}

Advanced Features

Automatic Entity Counting

The bundle automatically tracks entity counts through Doctrine events:

use CounterBundle\Provider\EntityTotalCountProvider;

class YourEntity
{
    // Your entity definition
}

// The counter will be automatically updated on entity creation/deletion

Performance Optimization

For large tables (>1M records), the bundle uses information_schema for count estimation:

// Automatically switches to estimation for large tables
$counter = $counterRepository->findOneBy(['name' => 'large.table.total']);

Scheduled Updates

Counter values are automatically updated via a cron job:

// Runs every hour at minute 30
#[AsCronTask('30 * * * *')]
#[AsCommand(name: 'counter:refresh-counter')]
class RefreshCounterCommand extends LockableCommand
{
    // Command implementation
}

Contributing

Please see CONTRIBUTING.md for details.

License

The MIT License (MIT). Please see License File for more information.