Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Stats Tables Cleaner Bundle Laravel Package

d3nysm/stats-tables-cleaner-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require d3nysm/stats-tables-cleaner-bundle
    

    Register the bundle in config/bundles.php (Laravel uses autoloading, so this step is optional but recommended for clarity).

  2. Annotate Your Entity Add the @CleanOldData annotation to any entity with a date/datetime column:

    use D3nysm\Bundle\StatsTablesCleaner\Annotation\CleanOldData;
    
    /**
     * @CleanOldData(interval="-1 month")
     */
    class StatsEntry { ... }
    
  3. Run the Command Test the cleanup with:

    php bin/console stats-tables-cleaner:clean
    

First Use Case

Clean up old logs or analytics data (e.g., user_activity_logs, api_requests) older than 30 days:

/**
 * @CleanOldData(interval="-30 days", batchSize=1000)
 */
class UserActivityLog { ... }

Implementation Patterns

Workflow Integration

  1. Event-Driven Cleanup Trigger cleanup via a cron job (e.g., daily at 2 AM):

    0 2 * * * cd /path/to/project && php bin/console stats-tables-cleaner:clean
    

    Or integrate with Laravel’s task scheduler (app/Console/Kernel.php):

    protected function schedule(Schedule $schedule) {
        $schedule->command('stats-tables-cleaner:clean')->daily();
    }
    
  2. Batch Processing For large tables, use batchSize to avoid memory issues:

    /**
     * @CleanOldData(interval="-6 month", batchSize=2000)
     */
    class ApiRequest { ... }
    
  3. Custom Events Hook cleanup to business events (e.g., after a user deletes their account):

    // In a service or controller
    $this->get('stats_tables_cleaner.cleaner')->clean('App\Entity\StatsEntry');
    

Advanced Patterns

  • Dynamic Intervals Override the interval via CLI arguments:

    php bin/console stats-tables-cleaner:clean --interval="-60 days"
    
  • Multi-Entity Cleanup Clean multiple tables in one command by extending the bundle or using a custom service:

    $cleaner->clean(['App\Entity\StatsEntry', 'App\Entity\UserActivityLog']);
    
  • Dry Run Mode Test cleanup without deleting data (add a --dry-run flag to the command).


Gotchas and Tips

Pitfalls

  1. Missing Indexes Ensure your date column is indexed (as shown in the @ORM\Table example). Without an index, cleanup will be slow:

    @ORM\Table(indexes={@ORM\Index(name="stat_date", columns={"date"})})
    
  2. Transaction Handling The bundle uses Doctrine transactions by default. For very large deletions, manually chunk transactions to avoid timeouts:

    // In a custom service
    $entityManager->beginTransaction();
    try {
        // Delete in batches
        $entityManager->commit();
    } catch (\Exception $e) {
        $entityManager->rollback();
        throw $e;
    }
    
  3. Annotation Parsing If annotations aren’t detected, clear Laravel’s cache:

    php artisan cache:clear
    
  4. Timezone Awareness Intervals (e.g., -3 month) use the system timezone. Explicitly set timezone in your app if needed:

    date_default_timezone_set('UTC');
    

Debugging Tips

  • Log Output Enable verbose mode for detailed logs:

    php bin/console stats-tables-cleaner:clean -v
    
  • Query Inspection Use Doctrine’s query logging to verify SQL:

    // In config/packages/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    

Extension Points

  1. Custom Cleaner Logic Extend the base cleaner to add pre/post-cleanup hooks:

    namespace App\Service;
    
    use D3nysm\Bundle\StatsTablesCleaner\Cleaner\CleanerInterface;
    
    class CustomCleaner implements CleanerInterface {
        public function clean(string $entityClass, \DateTimeInterface $cutoff): int {
            // Custom logic here
            return $deletedCount;
        }
    }
    
  2. Dynamic Entity Discovery Override the entity finder to exclude/include specific tables:

    // In services.yaml
    D3nysm\Bundle\StatsTablesCleaner\Cleaner\EntityFinder:
        arguments:
            $entityClasses: ['App\Entity\StatsEntry', 'App\Entity\ApiRequest']
    
  3. Event Listeners Dispatch events before/after cleanup (e.g., notify Slack):

    // In a listener
    public function onCleanup(StatsTablesCleanerEvent $event) {
        if ($event->isDryRun()) {
            // Send notification
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle