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

Cms Analytics Bundle Laravel Package

canabelle/cms-analytics-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require canabelle/cms-analytics-bundle
    

    Add to config/bundles.php:

    Canabelle\CMSAnalyticsBundle\CanabelleCMSAnalyticsBundle::class => ['all' => true],
    
  2. Configuration: Place your Google Analytics authentication JSON key file in config/packages/cms_analytics.json. Define your GA profile ID in config/packages/cms_analytics.yml:

    cms_analytics:
        profile_id: "UA-XXXXXXXX-X"
    
  3. First Use Case: Inject the service in a controller to fetch basic analytics data:

    use Canabelle\CMSAnalyticsBundle\Service\AnalyticsService;
    
    class DashboardController extends Controller
    {
        public function show(AnalyticsService $analytics)
        {
            $data = $analytics->getData();
            return view('dashboard', compact('data'));
        }
    }
    

Implementation Patterns

Integration with SonataAdmin

Extend SonataAdmin to include analytics in the dashboard:

# config/packages/sonata_admin.yml
sonata_admin:
    dashboard:
        groups:
            analytics:
                label: Analytics
                label_catalogue: sonata_admin
                icon: '<i class="fa fa-bar-chart"></i>'
                items:
                    - Canabelle\CMSAnalyticsBundle\Admin\AnalyticsAdmin

Common Workflows

  1. Fetching Reports: Use the AnalyticsService to retrieve metrics like:

    $service->getVisitors(); // Total visitors
    $service->getPageViews(); // Page views
    $service->getTrafficSources(); // Traffic sources breakdown
    
  2. Custom Reports: Extend the service to fetch custom dimensions/metrics:

    $service->getCustomReport('ga:sessions', [
        'dimensions' => 'ga:date,ga:pagePath',
        'metrics' => 'ga:sessions,ga:pageviews',
    ]);
    
  3. Caching: Cache responses for performance (e.g., using Symfony Cache component):

    $cache = $this->container->get('cache.app');
    $key = 'analytics_data_' . $profileId;
    $data = $cache->get($key, function() use ($analytics) {
        return $analytics->getData();
    });
    
  4. Event Listeners: Trigger analytics updates via events (e.g., after content is published):

    // src/EventListener/AnalyticsListener.php
    public function onContentPublish(ContentPublishEvent $event)
    {
        $analytics = $this->container->get('analytics');
        $analytics->trackEvent('content', 'publish', $event->getContent()->getSlug());
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication:

    • Ensure the JSON key file (cms_analytics.json) has the correct permissions (chmod 600).
    • The file must be placed in config/packages/ or configured in config/packages/cms_analytics.yml:
      cms_analytics:
          auth_key_path: "%kernel.project_dir%/config/packages/custom_ga_key.json"
      
  2. Deprecated API:

    • The bundle uses the v3 GA API, which is deprecated. Plan to migrate to GA4 or Measurement Protocol if long-term support is needed.
    • Errors like Invalid Credentials may appear if the key file is misconfigured or revoked.
  3. Profile ID:

    • Double-check the profile_id in cms_analytics.yml (e.g., UA-XXXXXXXX-X). Using a view ID (e.g., 12345678) will fail.
  4. Rate Limits:

    • The free tier of GA API has strict quotas (~50k requests/day). Cache aggressively or implement batching for large datasets.

Debugging

  • Enable Debugging: Set debug: true in cms_analytics.yml to log API responses:

    cms_analytics:
        debug: true
    

    Check logs in var/log/dev.log.

  • API Errors: Handle exceptions gracefully:

    try {
        $data = $analytics->getData();
    } catch (\Google\ApiCore\ApiException $e) {
        $this->addFlash('error', 'Analytics API error: ' . $e->getMessage());
        return $this->redirectToRoute('dashboard');
    }
    

Extension Points

  1. Custom Metrics: Extend the AnalyticsService to add methods for niche use cases:

    // src/Service/ExtendedAnalyticsService.php
    class ExtendedAnalyticsService extends AnalyticsService
    {
        public function getConversionRate()
        {
            $goals = $this->getGoals();
            $sessions = $this->getSessions();
            return $goals / $sessions * 100;
        }
    }
    

    Register as a service in config/services.yaml:

    services:
        App\Service\ExtendedAnalyticsService:
            decorates: 'analytics'
            arguments: ['@.inner']
    
  2. Multi-Property Support: Override the service to support multiple GA profiles:

    public function getDataForProfile($profileId)
    {
        $this->profileId = $profileId;
        return $this->fetchData();
    }
    
  3. Sonata Dashboard Widget: Create a custom widget for SonataAdmin:

    // src/Admin/AnalyticsDashboardWidget.php
    class AnalyticsDashboardWidget extends AbstractDashboardWidget
    {
        public function execute(AnalyticsService $analytics)
        {
            $this->data = $analytics->getVisitors();
        }
    
        public function getTemplate()
        {
            return '@CanabelleCMSAnalytics/analytics_widget.html.twig';
        }
    }
    

    Register in sonata_admin.yml:

    dashboard:
        widgets:
            - { service: 'analytics_dashboard_widget', positions: ['right'] }
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle