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

Google Charts Bundle Laravel Package

cmen/google-charts-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cmen/google-charts-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        CMEN\GoogleChartsBundle\CMENGoogleChartsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: In a Twig template, load the chart extension:

    {% use 'CMENGoogleChartsBundle:Chart:chart' %}
    

    Render a basic pie chart:

    {{ chart('pie', {
        'title': 'Sample Pie Chart',
        'data': [
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]
    }) }}
    
  3. Key Files to Review:

    • Resources/doc/basic_usage.md (for syntax)
    • Resources/doc/cookbook.md (for real-world examples)
    • Resources/doc/events.md (for customization hooks)

Implementation Patterns

Core Workflow

  1. Data Preparation: Use PHP objects (CMEN\GoogleChartsBundle\Chart\Chart) to structure data before passing to Twig:

    use CMEN\GoogleChartsBundle\Chart\Chart;
    
    $chart = new Chart('pie');
    $chart->setTitle('Sales by Region')
          ->addRow(['Region', 'Sales'])
          ->addRow(['North', 1000])
          ->addRow(['South', 1500]);
    
  2. Twig Integration: Render charts in templates with dynamic data:

    {{ chart(chartType, chartData, {
        'width': '600px',
        'height': '400px',
        'options': {
            'title': 'Dynamic Title',
            'is3D': true
        }
    }) }}
    
  3. Reusable Components: Create a base controller method to standardize chart generation:

    public function renderChart(string $type, array $data, array $options = []): string
    {
        return $this->renderView('chart/_template.html.twig', [
            'chart' => $this->buildChart($type, $data, $options),
        ]);
    }
    

Advanced Patterns

  • Dynamic Data Binding: Fetch data from repositories and pass to charts:

    {% set chartData = app.service('app.repository.sales').findByRegion() %}
    {{ chart('column', chartData, { 'options': { 'hAxis': { 'title': 'Months' } } }) }}
    
  • Event-Driven Customization: Subscribe to CMENGoogleChartsBundle.Event\ChartEvent to modify chart behavior:

    // src/EventListener/ChartCustomizer.php
    public function onChartBuild(ChartEvent $event)
    {
        $event->getChart()->addJavaScript('google.charts.load("current", {packages: ["corechart"]});');
    }
    
  • Diff Charts: Use the diff chart type for A/B comparisons:

    {{ chart('diff', {
        'title': 'Version Comparison',
        'data': [
            ['Version', 'Score'],
            ['1.0', 80],
            ['2.0', 95]
        ]
    }) }}
    

Gotchas and Tips

Common Pitfalls

  1. JavaScript Dependencies:

    • Ensure Google Charts API is loaded before rendering charts. Use the bundle’s addJavaScript method or include it in your base layout:
      <script src="https://www.gstatic.com/charts/loader.js"></script>
      
    • Debug missing charts by checking browser console for google.charts errors.
  2. Data Format Strictness:

    • Google Charts expects 2D arrays for most chart types. Flatten nested data:
      // Bad: [[['A', 1], ['B', 2]]] → Fix: [['A', 1], ['B', 2]]
      $chart->addRows(flatten($nestedData));
      
  3. Caching Issues:

    • Charts may not update if cached. Use unique IDs or timestamps in chart options:
      {{ chart('line', data, { 'id': 'chart-' ~ now().uniqid() }) }}
      

Debugging Tips

  • Inspect Rendered HTML: View the generated <div> structure to verify data binding:
    {{ dump(chart('pie', data)) }} {# Debug data structure #}
    
  • Check Console Logs: Google Charts logs errors to the browser console. Look for:
    • Failed to load resource (API not loaded).
    • Invalid argument (malformed data).

Configuration Quirks

  1. Default Options: Override defaults in config/packages/cmen_google_charts.yaml:

    cmen_google_charts:
        default_options:
            chartArea: { width: '90%', height: '70%' }
            legend: { position: 'bottom' }
    
  2. Chart Type Limitations:

    • Not all Google Chart types are supported. Refer to Google’s docs for compatibility.
    • Use CMEN\GoogleChartsBundle\Chart\Chart::setType() for unsupported types (may require manual JS).

Extension Points

  1. Custom Chart Types: Extend the bundle by creating a new chart class:

    class CustomChart extends AbstractChart
    {
        public function __construct()
        {
            $this->setType('customType');
            $this->addJavaScript('google.charts.load("current", {packages: ["customchart"]});');
        }
    }
    
  2. Twig Function Overrides: Override the Twig extension in your bundle’s Resources/config/services.yaml:

    services:
        app.twig.extension.google_charts:
            class: App\Twig\ExtendedGoogleChartsExtension
            tags: ['twig.extension']
    
  3. Event-Based Extensions: Use ChartEvent to inject custom logic:

    // src/EventSubscriber/ChartSubscriber.php
    public static function getSubscribedEvents()
    {
        return [
            ChartEvent::PRE_BUILD => 'onPreBuild',
            ChartEvent::POST_BUILD => 'onPostBuild',
        ];
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware