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

Products Viewed Laravel Package

baks-dev/products-viewed

Laravel/PHP модуль для отслеживания и вывода просмотренных товаров. Установка через Composer, рендер в Twig: render_products_viewed(invariable_id|null). Поддерживает установку ассетов, миграции Doctrine и тесты PHPUnit.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require baks-dev/products-viewed
    php artisan vendor:publish --provider="BaksDev\ProductsViewed\ProductsViewedServiceProvider" --tag="config"
    php bin/console baks:assets:install
    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  2. Enable Middleware Add the middleware to your app/Http/Kernel.php under the $middleware or $middlewareGroups['web'] array:

    \BaksDev\ProductsViewed\Http\Middleware\TrackProductViewed::class,
    
  3. First Use Case Track product views by passing the invariable_id (or product_id) to your Twig template:

    {% set productId = product.invariable_id %}
    {{ render_products_viewed(productId) }}
    

    Ensure your route/controller passes the product entity to the view.


Where to Look First

  • Configuration: Review config/products-viewed.php for:
    • tracking_limit: Max views per session/user.
    • storage: Database/table settings (default: products_viewed).
    • middleware: Custom middleware for view tracking logic.
  • Middleware: Inspect TrackProductViewed in app/Http/Middleware/ to understand how views are captured (e.g., via session or request data).
  • Twig Extension: Check BaksDev\ProductsViewed\Twig\ProductsViewedExtension for template methods and customization points.
  • Entities: Review BaksDev\ProductsViewed\Entity\ProductViewed for database schema and relationships.

Implementation Patterns

Core Integration Patterns

1. Middleware-Driven Tracking

  • Pattern: Use TrackProductViewed middleware to auto-capture views when products are accessed.
  • Workflow:
    1. Add middleware to Kernel.php.
    2. Ensure product routes pass the invariable_id (or product_id) in the request.
    3. The middleware stores the view in the database and session.
  • Example:
    // In your controller
    public function show(Product $product) {
        return view('product.show', ['product' => $product]);
    }
    
    The middleware automatically logs the view when the route is hit.

2. Twig Template Integration

  • Pattern: Render tracked views in templates using the render_products_viewed Twig function.
  • Workflow:
    1. Pass the invariable_id to the template.
    2. Use the Twig function to display recent views or related products.
  • Example:
    {# Show recently viewed products #}
    {{ render_products_viewed(user.id, 5) }}
    
  • Customization: Extend the Twig extension to modify rendering logic (e.g., filters, sorting).

3. Event-Driven Extensions

  • Pattern: Listen for ProductViewed events to trigger side effects (e.g., analytics, recommendations).
  • Workflow:
    1. Publish the event config:
      php artisan vendor:publish --provider="BaksDev\ProductsViewed\ProductsViewedServiceProvider" --tag="events"
      
    2. Register a listener:
      // app/Listeners/ProductViewedListener.php
      public function handle(ProductViewed $event) {
          // Send to analytics, update recommendations, etc.
      }
      
    3. Bind the listener in EventServiceProvider:
      protected $listen = [
          \BaksDev\ProductsViewed\Events\ProductViewed::class => [
              \App\Listeners\ProductViewedListener::class,
          ],
      ];
      

4. API Integration

  • Pattern: Expose tracked views via API for frontend or third-party tools.
  • Workflow:
    1. Create a controller:
      // app/Http/Controllers/ProductViewedController.php
      public function index(Request $request) {
          $views = ProductViewedRepository::getRecentViews($request->user(), 10);
          return response()->json($views);
      }
      
    2. Add a route:
      Route::get('/api/products/viewed', [ProductViewedController::class, 'index']);
      
    3. Use the API in your frontend or analytics pipeline.

5. Caching Recent Views

  • Pattern: Cache frequently accessed views (e.g., "recently viewed") to reduce database load.
  • Workflow:
    1. Extend the ProductViewedRepository to use Redis:
      public function getRecentViews(User $user, int $limit) {
          $cacheKey = "recent_views_{$user->id}";
          return Cache::remember($cacheKey, now()->addHours(1), function() use ($user, $limit) {
              return $this->entityManager->getRepository(ProductViewed::class)
                  ->findBy(['user' => $user->id], ['created_at' => 'DESC'], $limit);
          });
      }
      

Advanced Patterns

1. Custom Storage Backends

  • Pattern: Replace the default database storage with a custom backend (e.g., Elasticsearch, DynamoDB).
  • Workflow:
    1. Implement BaksDev\ProductsViewed\Contracts\ViewStorageInterface.
    2. Bind your implementation in the service provider:
      $this->app->bind(
          ViewStorageInterface::class,
          CustomViewStorage::class
      );
      

2. Bulk View Tracking

  • Pattern: Track views in bulk (e.g., for API imports or cron jobs).
  • Workflow:
    1. Use the repository directly:
      $repository = $this->container->get(ProductViewedRepository::class);
      $repository->bulkTrack([
          ['user_id' => 1, 'product_id' => 101, 'created_at' => now()],
          ['user_id' => 2, 'product_id' => 102, 'created_at' => now()],
      ]);
      

3. View Retention Policies

  • Pattern: Automate cleanup of old views to manage database size.
  • Workflow:
    1. Schedule a command (e.g., via Laravel Scheduler):
      // app/Console/Commands/CleanupProductViews.php
      public function handle() {
          $this->entityManager->getRepository(ProductViewed::class)
              ->createQueryBuilder('pv')
              ->delete()
              ->where('pv.created_at < :date')
              ->setParameter('date', now()->subMonths(6))
              ->getQuery()
              ->execute();
      }
      
    2. Add to app/Console/Kernel.php:
      $schedule->command(CleanupProductViews::class)->monthly();
      

4. Multi-Tenant Support

  • Pattern: Track views per tenant in a multi-tenant application.
  • Workflow:
    1. Extend the ProductViewed entity to include a tenant_id field.
    2. Update migrations and queries to scope by tenant:
      $repository->findBy(['user' => $user->id, 'tenant_id' => tenant()->id()]);
      

Gotchas and Tips

Pitfalls

  1. Middleware Timing

    • Issue: Views may not track if the middleware runs after the product is rendered (e.g., due to route grouping).
    • Fix: Ensure TrackProductViewed is placed before any middleware that might alter the request (e.g., authentication, localization).
  2. Database Schema Conflicts

    • Issue: The package’s products_viewed table may conflict with existing tables.
    • Fix: Customize the migration or table name in config:
      'storage' => [
          'table' => 'custom_product_views',
      ],
      
  3. Twig vs. Blade

    • Issue: The package assumes Twig. Blade users must create a helper or directive.
    • Fix: Add a Blade directive:
      // app/Providers/BladeServiceProvider.php
      Blade::directive('renderProductsViewed', function ($expression) {
          return "<?php echo app('BaksDev\\ProductsViewed\\Twig\\ProductsViewedExtension')->renderProductsViewed({$expression}); ?>";
      });
      
      Usage:
      @renderProductsViewed($product->invariable_id)
      
  4. Performance with High Traffic

    • Issue: Database inserts during peak traffic may slow responses.
    • Fix: Queue the view tracking:
      // In TrackProductViewed middleware
      TrackProductView::dispatch($productId, $userId)->onQueue('product-views');
      
      Then create a job:
      // app/Jobs/TrackProductView.php
      public function handle()
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky