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

Stat Bundle Laravel Package

da/stat-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require gnuckorg/dastat-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Gnuckorg\DaStatBundle\DaStatBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Basic Statistic Define a simple statistic loader in src/Statistic/Loader/MyStatisticLoader.php:

    namespace App\Statistic\Loader;
    
    use Gnuckorg\DaStatBundle\Loader\LoaderInterface;
    
    class MyStatisticLoader implements LoaderInterface
    {
        public function load(): array
        {
            return [
                'total_users' => 100,
                'active_users' => 50,
            ];
        }
    }
    
  3. Register the Loader Add the loader to config/packages/dastat.yaml:

    dastat:
        loaders:
            - App\Statistic\Loader\MyStatisticLoader
    
  4. Render the Statistic Use the statistic Twig function in a template:

    {% statistic('total_users') %}
    

Implementation Patterns

Common Workflows

  1. Data Loading Patterns

    • Database Queries: Fetch data from repositories or query builders.
      public function load(): array
      {
          return $this->entityManager->getRepository(User::class)
              ->createQueryBuilder('u')
              ->select('COUNT(u.id)')
              ->getQuery()
              ->getSingleScalarResult();
      }
      
    • API Integration: Load data from external APIs.
      public function load(): array
      {
          $response = $this->httpClient->request('GET', 'https://api.example.com/stats');
          return json_decode($response->getContent(), true);
      }
      
    • Caching: Cache results to avoid repeated expensive operations.
      public function load(): array
      {
          return $this->cache->get('stats_key', function () {
              return $this->fetchExpensiveData();
          });
      }
      
  2. Rendering Patterns

    • Twig Extensions: Use the provided Twig functions for dynamic rendering.
      {% statistic('total_orders', 'default') %}
      {% statistic('active_users', 'active_users_template') %}
      
    • Custom Templates: Override default rendering logic by creating custom Twig templates in templates/dastat/.
  3. Dependency Injection

    • Inject services into loaders via constructor.
      public function __construct(private EntityManagerInterface $em, private HttpClientInterface $http)
      {
      }
      
  4. Tagging Loaders

    • Use Symfony’s tags to dynamically register loaders (e.g., for per-environment stats).
      # config/services.yaml
      services:
          App\Statistic\Loader\DevStatLoader:
              tags: ['dastat.loader']
      

Integration Tips

  • Event Listeners: Trigger stat updates on relevant events (e.g., kernel.terminate for periodic updates).
    public function onKernelTerminate(KernelEvents::TERMINATE, Event $event)
    {
        $this->statisticManager->updateAll();
    }
    
  • Command Line: Create a console command to manually refresh stats.
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class RefreshStatsCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $this->statisticManager->updateAll();
            $output->writeln('Stats refreshed!');
            return Command::SUCCESS;
        }
    }
    
  • Security: Restrict access to sensitive stats using Symfony’s security system.
    # config/packages/security.yaml
    access_control:
        - { path: ^/admin/stats, roles: ROLE_ADMIN }
    

Gotchas and Tips

Pitfalls

  1. Loader Naming Collisions

    • Ensure loader class names are unique to avoid conflicts. Prefix with your bundle namespace (e.g., App\Statistic\Loader\).
  2. Circular Dependencies

    • Avoid circular dependencies between loaders. Use DTOs or intermediate services to decouple logic.
  3. Performance Overhead

    • Heavy loaders (e.g., those querying large datasets) can slow down your application. Cache results aggressively or run them asynchronously (e.g., via Symfony Messenger).
  4. Twig Template Overrides

    • If custom templates aren’t picked up, verify they’re placed in templates/dastat/ and named correctly (e.g., active_users.html.twig).
  5. Configuration Merging

    • Be cautious when merging configurations in dastat.yaml. Overrides may not behave as expected if the bundle’s default config isn’t accounted for.

Debugging

  1. Loader Errors

    • Check the dastat.log channel (configured in config/packages/monolog.yaml) for loader-specific errors.
      monolog:
          channels: ['dastat']
      
  2. Missing Stats

    • Verify loaders are registered in dastat.yaml and tagged as dastat.loader if using dynamic registration.
    • Clear the cache after adding new loaders:
      php bin/console cache:clear
      
  3. Twig Rendering Issues

    • Ensure the DaStatBundle Twig extension is enabled (it should be by default).
    • Debug Twig template paths with:
      php bin/console debug:twig
      

Tips

  1. Modular Design

    • Group related stats into separate loaders (e.g., UserStatsLoader, OrderStatsLoader) for better maintainability.
  2. Type Safety

    • Use PHP 8’s typed properties and return types to catch loader errors early.
      public function load(): array {
          return [...];
      }
      
  3. Testing

    • Mock loaders in unit tests to isolate statistic logic.
      $loader = $this->createMock(MyStatisticLoader::class);
      $loader->method('load')->willReturn(['test' => 123]);
      $this->container->set(MyStatisticLoader::class, $loader);
      
  4. Documentation

    • Add PHPDoc blocks to loaders to clarify their purpose and output structure.
      /**
       * Loads user-related statistics.
       * @return array{
       *     total: int,
       *     active: int,
       *     registered_today: int
       * }
       */
      public function load(): array { ... }
      
  5. Extending the Bundle

    • Override the bundle’s services in config/services.yaml to customize behavior.
      services:
          Gnuckorg\DaStatBundle\Manager\StatisticManager:
              arguments:
                  $cachePool: '@cache.app'
      
  6. Environment-Specific Stats

    • Use Symfony’s parameter system to enable/disable loaders per environment.
      # config/packages/dastat.yaml
      dastat:
          enabled_loaders: '%kernel.environment%::dev' ? ['DevStatLoader'] : ['ProdStatLoader']
      
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony