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

Views Counter Bundle Laravel Package

cengizhancaliskan/views-counter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cengizhancaliskan/views-counter-bundle
    

    Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    Cengizhan\ViewsCounterBundle\CengizhanViewsCounterBundle::class => ['all' => true],
    
  2. Annotate an Entity Implement VisitableInterface and use VisitableEntityTrait:

    use Cengizhan\ViewsCounterBundle\Model\VisitableInterface;
    use Cengizhan\ViewsCounterBundle\Traits\VisitableEntityTrait;
    
    class Article implements VisitableInterface
    {
        use VisitableEntityTrait;
        // ...
    }
    
  3. First Use Case Increment views in a controller:

    $this->get('views_counter.views_counter')->count($article);
    

Implementation Patterns

Core Workflow

  1. View Tracking Call count() in your controller after rendering the view (e.g., in showAction):

    public function show(Article $article)
    {
        return $this->render('article/show.html.twig', ['article' => $article]);
        // Then increment:
        $this->get('views_counter.views_counter')->count($article);
    }
    
  2. Event-Based Integration Use Symfony events to automate counting (e.g., kernel.view):

    # config/services.yaml
    services:
        App\EventListener\ViewCounterListener:
            tags:
                - { name: kernel.event_listener, event: kernel.view, method: onKernelView }
    
    // src/EventListener/ViewCounterListener.php
    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $controller = $event->getController();
        if (is_array($controller) && $controller[0] instanceof ArticleController) {
            $article = $controller[1]->getArticle(); // Adjust based on your logic
            $this->get('views_counter.views_counter')->count($article);
        }
    }
    
  3. Query Builder Integration Fetch top-viewed entities:

    $topArticles = $this->getDoctrine()
        ->getRepository(Article::class)
        ->createQueryBuilder('a')
        ->orderBy('a.views', 'DESC')
        ->setMaxResults(5)
        ->getQuery()
        ->getResult();
    

Advanced Patterns

  • Custom Logic: Override VisitableEntityTrait methods (e.g., getViewsColumn()).
  • Batch Updates: Use Doctrine batch processing for bulk view increments:
    $em = $this->getDoctrine()->getManager();
    $articles = $em->getRepository(Article::class)->findAll();
    foreach ($articles as $article) {
        $article->incrementViews();
    }
    $em->flush();
    

Gotchas and Tips

Pitfalls

  1. Double Counting

    • Risk: Calling count() multiple times in a single request (e.g., AJAX + page load).
    • Fix: Wrap in a service with a flag or use Symfony’s RequestStack to check for duplicates.
  2. Outdated ORM

    • The bundle uses IDENTITY strategy (deprecated in Doctrine 2.5+). Update to AUTO or SEQUENCE if needed.
  3. Performance

    • Issue: Frequent flush() calls on high-traffic pages.
    • Fix: Batch updates or use a queue system (e.g., Symfony Messenger).
  4. Archived Status

    • Warning: No updates since 2017. Test thoroughly in staging before production use.

Debugging Tips

  • Verify Entity Mapping: Ensure views column exists in your database table:
    php bin/console doctrine:schema:validate
    
  • Check Service Availability: Confirm the service is registered:
    php bin/console debug:container views_counter.views_counter
    
  • Log Increments: Add logging to debug:
    $this->get('logger')->info('Incremented views for article ID: ' . $article->getId());
    

Extension Points

  1. Custom Columns Override getViewsColumn() in your entity to use a non-standard column name.

  2. Conditional Counting Extend the VisitableInterface to add logic (e.g., skip counting for admins):

    public function shouldCountView(): bool
    {
        return !$this->isAdminView();
    }
    
  3. Alternative Storage Replace the Doctrine-based counter with a Redis-backed solution by extending the ViewsCounter service.

  4. Symfony 5+ Compatibility Update composer.json to require ^5.0 and adjust autowiring if needed:

    # config/services.yaml
    Cengizhan\ViewsCounterBundle\ViewsCounter:
        arguments:
            $entityManager: '@doctrine.orm.entity_manager'
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope