PHPackages                             tourze/counter-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tourze/counter-bundle

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

tourze/counter-bundle
=====================

Symfony Counter Bundle

1.0.1(6mo ago)02581MITPHPCI passing

Since Apr 8Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/counter-bundle)[ Packagist](https://packagist.org/packages/tourze/counter-bundle)[ RSS](/packages/tourze-counter-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (35)Versions (10)Used By (1)

Counter Bundle
==============

[](#counter-bundle)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/a299b1e4527e85d14bde1304ce4a097bea9a1c2621c57ce20202bbfe2833fdac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f636f756e7465722d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/counter-bundle)[![Total Downloads](https://camo.githubusercontent.com/08c0fdb50f796ab143e8c2595f04ae89ef4443ba51690c408067741156e3b4a2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f636f756e7465722d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/counter-bundle)[![PHP Version](https://camo.githubusercontent.com/57bf50bbb54980de9c095bc94cfb7aceb6b002fe0d35f544034037aca2cfd93b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f636f756e7465722d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/counter-bundle)[![License](https://camo.githubusercontent.com/997f78b0e1d41698e4a93c1dfbd916fb13250190af09a21b9087ecf85aa99b65/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f636f756e7465722d62756e646c652e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Code Coverage](https://camo.githubusercontent.com/51ceeb459b697a9c0d5c37e0b9e25169e5376069462c3b6d7dd0952037bbe202/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f636f756e7465722d62756e646c653f7374796c653d666c61742d737175617265)](https://codecov.io/gh/tourze/counter-bundle)

A high-performance Symfony bundle for managing counters and statistics with automatic entity counting, manual operations, and scheduled updates.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Requirements](#requirements)
- [Configuration](#configuration)
- [Usage](#usage)
- [Advanced Features](#advanced-features)
- [Architecture](#architecture)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- 🚀 **Automatic Entity Counting** - Tracks entity counts through Doctrine events
- 📊 **Performance Optimized** - Uses estimation for large tables (&gt;1M records)
- 🔄 **Real-time Updates** - Counters update automatically on entity changes
- ⏰ **Scheduled Refresh** - Cron-based counter synchronization
- 🎯 **Custom Providers** - Extensible counter provider system
- 🔒 **Thread-safe Operations** - Lock mechanism prevents concurrent updates
- 📝 **Context Support** - Store additional metadata with counters

Installation
------------

[](#installation)

```
composer require tourze/counter-bundle

```

Requirements
------------

[](#requirements)

- PHP 8.1+
- Symfony 6.4+
- Doctrine ORM 3.0+

Configuration
-------------

[](#configuration)

### 1. Enable the Bundle

[](#1-enable-the-bundle)

Register the bundle in `config/bundles.php`:

```
return [
    // ...
    CounterBundle\CounterBundle::class => ['all' => true],
];

```

### 2. Update Database Schema

[](#2-update-database-schema)

```
# Create the counter table
php bin/console doctrine:schema:update --force

# Or use migrations
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate

```

Usage
-----

[](#usage)

### Basic Counter Operations

[](#basic-counter-operations)

```
use CounterBundle\Repository\CounterRepository;
use CounterBundle\Provider\EntityTotalCountProvider;

class StatisticsService
{
    public function __construct(
        private readonly CounterRepository $counterRepository,
        private readonly EntityTotalCountProvider $countProvider
    ) {}

    public function getStatistics(): array
    {
        // Get counter by name
        $userCounter = $this->counterRepository->findOneBy([
            'name' => 'App\Entity\User::total'
        ]);

        // Manual increment/decrement
        $this->countProvider->increaseEntityCounter('App\Entity\Product');
        $this->countProvider->decreaseEntityCounter('App\Entity\Product');

        return [
            'users' => $userCounter?->getCount() ?? 0,
            'products' => $this->counterRepository->findOneBy([
                'name' => 'App\Entity\Product::total'
            ])?->getCount() ?? 0,
        ];
    }
}

```

### Automatic Entity Counting

[](#automatic-entity-counting)

The bundle automatically tracks entity counts through Doctrine listeners:

```
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    // ... other properties
}

// Counters are automatically created:
// - "App\Entity\Product::total" - Total count of products

```

### Custom Counter Providers

[](#custom-counter-providers)

Create custom counters by implementing `CounterProvider`:

```
use CounterBundle\Provider\CounterProvider;
use CounterBundle\Entity\Counter;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag('app.counter.provider')]
class OrderStatisticsProvider implements CounterProvider
{
    public function __construct(
        private readonly OrderRepository $orderRepository
    ) {}

    public function getCounters(): iterable
    {
        // Pending orders counter
        $pendingCount = $this->orderRepository->count(['status' => 'pending']);
        $pendingCounter = new Counter();
        $pendingCounter->setName('orders.pending')
                      ->setCount($pendingCount)
                      ->setContext(['status' => 'pending']);
        yield $pendingCounter;

        // Completed orders counter
        $completedCount = $this->orderRepository->count(['status' => 'completed']);
        $completedCounter = new Counter();
        $completedCounter->setName('orders.completed')
                         ->setCount($completedCount)
                         ->setContext(['status' => 'completed']);
        yield $completedCounter;
    }
}

```

### Scheduled Updates

[](#scheduled-updates)

Counters are automatically refreshed every hour at minute 30:

```
# Run the refresh command manually
php bin/console counter:refresh-counter

# Or set up cron job
30 * * * * php /path/to/project/bin/console counter:refresh-counter

```

### Performance Optimization

[](#performance-optimization)

The bundle automatically optimizes counting for large tables:

```
// For tables with 1M records: uses table statistics from information_schema

$counter = $this->countProvider->getCounterByEntityClass(
    'App\Entity\LargeTable'
);
// Automatically uses estimation for performance

```

Advanced Features
-----------------

[](#advanced-features)

### Context Storage

[](#context-storage)

Store additional metadata with counters:

```
$counter = new Counter();
$counter->setName('api.requests')
        ->setCount(1000)
        ->setContext([
            'endpoint' => '/api/users',
            'method' => 'GET',
            'date' => '2024-01-01'
        ]);

```

### Event Listeners

[](#event-listeners)

The bundle provides event subscribers for automatic counting:

- `EntityListener` - Tracks entity creation/deletion
- Implements `ResetInterface` for memory management
- Uses batch processing to minimize database queries

### Console Commands

[](#console-commands)

```
# Refresh all counters
php bin/console counter:refresh-counter

# The command is lockable to prevent concurrent execution

```

Architecture
------------

[](#architecture)

### Components

[](#components)

- **Entity/Counter** - The main counter entity with timestamp support
- **Repository/CounterRepository** - Repository for counter operations
- **Provider/EntityTotalCountProvider** - Handles entity counting logic
- **EventSubscriber/EntityListener** - Tracks Doctrine events
- **Command/RefreshCounterCommand** - Scheduled counter updates

### Database Schema

[](#database-schema)

```
CREATE TABLE table_count (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL,
    count INT NOT NULL DEFAULT 0,
    context JSON,
    create_time DATETIME NOT NULL,
    update_time DATETIME NOT NULL
);

```

Best Practices
--------------

[](#best-practices)

1. **Use providers for complex counters** - Don't calculate counts in real-time for complex queries
2. **Leverage context** - Store filtering criteria in context for debugging
3. **Monitor performance** - Check logs for estimation warnings on large tables
4. **Regular updates** - Ensure cron job is running for accurate counts

Troubleshooting
---------------

[](#troubleshooting)

### Counters not updating

[](#counters-not-updating)

1. Check if entity listener is registered:

    ```
    php bin/console debug:event-dispatcher doctrine.orm.entity_manager

    ```
2. Verify cron job is running:

    ```
    php bin/console debug:command counter:refresh-counter

    ```

### Performance issues

[](#performance-issues)

1. Check table sizes:

    ```
    SELECT table_name, table_rows
    FROM information_schema.tables
    WHERE table_schema = 'your_database';

    ```
2. Monitor query performance in Symfony profiler

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

License
-------

[](#license)

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

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance72

Regular maintenance activity

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~27 days

Recently: every ~47 days

Total

9

Last Release

180d ago

Major Versions

0.1.3 → 1.0.02025-11-04

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (3 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-counter-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-counter-bundle/health.svg)](https://phpackages.com/packages/tourze-counter-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M648](/packages/sylius-sylius)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
