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

Chart Bundle Laravel Package

dgc/chart-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require dgc/chart-bundle
    

    Add to AppKernel.php:

    new DGC\ChartBundle\DGCChartBundle(),
    
  2. Include Dependencies Add to your base template (base.html.twig or similar):

    {% include '@DGCChart/Includes/lib_daterangepicker.html.twig' %}
    {% include '@DGCChart/Includes/lib_echarts.html.twig' %}
    {% include '@DGCChart/Includes/lib_morris.html.twig' %}
    
  3. First Chart (SQL Example) In a controller (e.g., TestController):

    use DGC\ChartBundle\Aggregator\SqlAggregator;
    
    public function indexAction()
    {
        $aggregator = $this->get('dgc_chart.factory.aggregator')->createSqlAggregator();
        $query = $aggregator
            ->setDatabaseConnection($this->get('doctrine.dbal.default_connection'))
            ->select('COUNT(*) as count')
            ->from('your_table')
            ->groupBy('category_column')
            ->build();
    
        $results = $query->fetchAll();
        return $this->render('test/index.html.twig', [
            'chartData' => $results,
        ]);
    }
    
  4. Render Chart in Twig

    {{ render_chart({
        'type': 'bar',
        'data': chartData,
        'options': {
            'title': { text: 'Sample Chart' }
        }
    }) }}
    

Implementation Patterns

Query Building Workflow

  1. Aggregator Factory Use dependency injection to fetch the aggregator:

    $sqlAggregator = $this->get('dgc_chart.factory.aggregator')->createSqlAggregator();
    $mongoAggregator = $this->get('dgc_chart.factory.aggregator')->createMongoAggregator();
    
  2. Query Chaining Chain methods for SQL queries:

    $query = $aggregator
        ->select('SUM(amount) as total')
        ->from('orders')
        ->where('created_at BETWEEN ? AND ?', [$startDate, $endDate])
        ->groupBy('YEAR(created_at)')
        ->orderBy('YEAR(created_at)')
        ->limit(10);
    
  3. MongoDB Support For MongoDB (Doctrine ODM):

    $mongoAggregator = $this->get('dgc_chart.factory.aggregator')->createMongoAggregator();
    $query = $mongoAggregator
        ->match(['status' => 'active'])
        ->group(['_id' => '$category', 'count' => ['$sum' => 1]])
        ->build();
    
  4. Dynamic Date Ranges Integrate with daterangepicker for user-driven date ranges:

    <input type="text" name="date-range" class="form-control" />
    <script>
        $(function() {
            $('input[name="date-range"]').daterangepicker();
        });
    </script>
    

    Pass selected dates to the controller and use them in queries.


Integration Tips

  1. Twig Extensions Use the render_chart Twig function for consistency:

    {{ render_chart({
        'type': 'line',
        'data': chartData,
        'library': 'echarts',  // or 'morris'
        'options': {
            'xAxis': { type: 'category' },
            'yAxis': { type: 'value' }
        }
    }) }}
    
  2. Reusable Chart Components Create base templates for common chart types (e.g., chart_bar.html.twig):

    {% extends 'base.html.twig' %}
    
    {% block body %}
        {{ render_chart({
            'type': 'bar',
            'data': data,
            'options': {
                'title': { text: title }
            }
        }) }}
    {% endblock %}
    
  3. API-Driven Charts Fetch chart data via API endpoints (e.g., GET /api/charts/sales) and render client-side:

    $.get('/api/charts/sales', function(data) {
        renderChart(data, 'echarts');
    });
    
  4. Caching Strategies Cache query results or rendered charts:

    // Cache query results for 1 hour
    $results = $this->get('dgc_chart.factory.aggregator')->createSqlAggregator()
        ->setDatabaseConnection($this->get('doctrine.dbal.default_connection'))
        ->select('...')
        ->cache(true, 3600)
        ->build()
        ->fetchAll();
    

Gotchas and Tips

Pitfalls

  1. Connection Configuration

    • Ensure doctrine.dbal.ext_connection or doctrine.odm.mongodb.default_connection is properly configured.
    • For custom connections, specify the service ID explicitly:
      $aggregator->setDatabaseConnection($this->get('your_custom_connection'));
      
  2. Library Dependencies

    • The bundle relies on external libraries (echarts, morris.js, daterangepicker). Ensure CORS and CDN availability if using self-hosted assets.
    • Test in a local environment first to avoid CDN-related rendering issues.
  3. Query Building Quirks

    • SQL Syntax: The query builder may not support all SQL dialects. Test with your specific DBMS (MySQL, PostgreSQL, etc.).
    • MongoDB Aggregation: Some MongoDB aggregation stages (e.g., $lookup) may require manual string interpolation:
      $aggregator->addStage('{$lookup: {from: "orders", localField: "_id", foreignField: "user_id", as: "orders"}}');
      
  4. Twig Rendering Issues

    • If render_chart fails, verify:
      • The data variable is properly passed to Twig.
      • The library option matches available libraries (echarts or morris).
      • Required JavaScript/CSS includes are loaded in the template.

Debugging

  1. Query Logs Enable Doctrine DBAL logging to debug SQL queries:

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  2. Aggregator Debugging Dump the raw query before execution:

    $query = $aggregator->build();
    dump($query->getSQL()); // For SQL
    // or
    dump($query->getMongoQuery()); // For MongoDB
    
  3. Chart Data Validation Validate chartData structure before rendering:

    {% if chartData is iterable %}
        {{ render_chart({...}) }}
    {% else %}
        <p>No data available.</p>
    {% endif %}
    

Extension Points

  1. Custom Chart Libraries Extend the bundle to support additional libraries (e.g., Chart.js):

    • Create a new Twig extension for render_chart_js.
    • Add corresponding JavaScript/CSS includes.
  2. Query Builder Extensions Add custom methods to the aggregator:

    // In a service or compiler pass
    $aggregator->addMethod('customGroup', function($field) {
        return $this->addRaw("GROUP BY CONCAT(YEAR({$field}), '-', MONTH({$field}))");
    });
    
  3. Dynamic Chart Types Use Twig macros to create dynamic chart templates:

    {% macro renderDynamicChart(type, data) %}
        {% if type == 'pie' %}
            {{ render_chart({
                'type': 'pie',
                'data': data,
                'library': 'echarts'
            }) }}
        {% elseif type == 'line' %}
            {{ render_chart({
                'type': 'line',
                'data': data,
                'library': 'morris'
            }) }}
        {% endif %}
    {% endmacro %}
    
  4. Event Listeners Hook into chart rendering events (e.g., post-render JavaScript execution):

    // In a service
    $eventDispatcher->addListener('dgc_chart.post_render', function($event) {
        $event->addScript("console.log('Chart rendered:', $event->getChartId());");
    });
    

Configuration Quirks

  1. Default Library Override the default chart library in config/packages/dgc_chart.yaml:

    dgc_chart:
        default_library: morris  # or 'echarts'
    
  2. Asset Management For production, replace CDN includes with local assets:

    {% block javascripts %}
        {{ parent() }}
        <script src="{{ asset('bundles/dgcchart/js/echarts.min.js') }}"></script>
    {% end
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor