Home > Backend Development > PHP Tutorial > Building OctoberCMS Plugins: Google Analytics

Building OctoberCMS Plugins: Google Analytics

Joseph Gordon-Levitt
Release: 2025-02-19 09:59:09
Original
167 people have browsed it

OctoberCMS Plugin Development: A Google Analytics Example

OctoberCMS is a rapidly growing content management system (CMS), and like all CMS platforms, its functionality is enhanced through plugins. This article provides a foundational guide to creating an OctoberCMS plugin, using a Google Analytics integration as a practical example.

Building OctoberCMS Plugins: Google Analytics

Key Concepts:

  • OctoberCMS's extensibility through plugins allows for seamless integrations, such as adding Google Analytics tracking.
  • The command-line interface simplifies plugin creation and management, supplementing the graphical interface within the CMS (System > Updates).
  • Components are crucial for user interaction; they are created via the command line or manually, requiring a dedicated 'components' folder.
  • Extensive customization is possible, including creating settings forms for user input (like the Google Analytics tracking ID), and retrieving these settings for use within components.

Project Overview:

We'll build a plugin that integrates Google Analytics tracking using a component tag. After configuring your tracking ID in the plugin's settings, you'll insert the component tag ({% component 'gaCode' %}) into your pages or partials to enable tracking. The complete code is available on GitHub.

Plugin Management:

OctoberCMS's plugins reside in the root directory's plugins folder. Management is handled through:

  • System > Updates: This page allows attaching projects (requiring an OctoberCMS account), adding marketplace plugins, and updating your website.
  • Command Line: Install plugins using the command line (though finding the plugin name on the website is necessary). The command format (at the time of writing) typically involves Author.PluginName.

Plugin Creation:

Creating a plugin is streamlined:

  • Manual Method: Create a new folder within the plugins directory. The folder name acts as your unique namespace (register your namespace on the OctoberCMS website to avoid conflicts). For this example, we'll use RAFIE.GoogleAnalyticsCode. Inside, create a Plugin.php file.
  • Scaffolding (Command Line): Use the command php artisan create:plugin RAFIE.GoogleAnalyticsCode. This automatically generates the necessary files and folders, including an uploads folder containing a version.yaml file for version control.

The Plugin.php file's pluginDetails() method (overriding SystemClassesPluginBase) defines the plugin:

public function pluginDetails() {
    return [
        'name'        => 'Google Analytics Code',
        'description' => 'Insert Google Analytics tracking code into your pages',
        'author'      => 'RAFIE Younes',
        'icon'        => 'icon-bar-chart-o'
    ];
}
Copy after login

If the plugin doesn't appear, click "Check for updates" to refresh the list.

Using Components:

Components enable interaction with the page. Create them manually (within a components folder) or via the command line:

php artisan create:component RAFIE.GoogleAnalyticsCode GoogleAnalytics
Copy after login

Building OctoberCMS Plugins: Google Analytics

The componentDetails() method (overriding CmsClassesComponentBase) defines the component's details for the admin dashboard. Register the component in Plugin.php's registerComponents() method:

public function registerComponents() {
    return [
        'RAFIE\GoogleAnalyticsCode\Components\GoogleAnalytics' => 'gaCode'
    ];
}
Copy after login

The component initially renders default.htm:

<p>></p>This is the default markup for component GoogleAnalytics>
<small>></small>You can delete this file if you want>
Copy after login

Replace this with the Google Analytics tracking code:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{{ code }}', 'auto');
ga('send', 'pageview');
Copy after login

Remember that the script should ideally be placed at the end of the page, depending on your theme.

Component Properties and Settings:

Instead of hardcoding the tracking ID, use component properties:

{% component 'gaCode' code='UA-12345678-1' %}
Copy after login

Define properties using defineProperties():

public function defineProperties() {
    return [
        'code' => [
            'title'             => 'Google Analytics tracking code',
            'description'       => 'Your Google Analytics tracking code',
            'default'           => '',
            'type'              => 'string',
            'validationPattern' => '^UA-\d{4,9}-\d{1,4}$',
            'validationMessage' => 'Invalid tracking code',
            'placeholder'       => 'UA-XXXXXXX'
        ]
    ];
}
Copy after login

Use onRender() to pass values to the page:

public function onRender() {
    $this->page['code'] = $this->property('code');
}
Copy after login

For a more user-friendly approach, use plugin settings:

Building OctoberCMS Plugins: Google Analytics

Create models/GoogleAnalyticsSettings.php:

class GoogleAnalyticsSettings extends Model {
    public $implement = ['System.Behaviors.SettingsModel'];
    public $settingsCode = 'rafie_google_analytics_code';
    public $settingsFields = 'fields.yaml';
}
Copy after login

Create models/fields.yaml:

fields:
  code:
    label: Your Google Analytics ID
    placeholder: UA-XXXXXXXX-X
Copy after login

Register settings in Plugin.php:

public function registerSettings() {
    return [
        'settings' => [
            'label'       => 'Google Analytics Code',
            'description' => 'Manage Google Analytics Settings',
            'icon'        => 'icon-bar-chart-o',
            'class'       => 'RAFIE\GoogleAnalyticsCode\Models\GoogleAnalyticsSettings',
            'order'       => 1
        ]
    ];
}
Copy after login

Building OctoberCMS Plugins: Google Analytics

Retrieve settings in onRender():

public function onRender() {
    $settings = GoogleAnalyticsSettings::instance();
    $this->page['code'] = $settings->code;
}
Copy after login

Conclusion:

OctoberCMS offers a robust and flexible plugin development system. This example demonstrates the core principles; further exploration of the source code and community resources will enhance your understanding.

Frequently Asked Questions (FAQs): (The provided FAQs are already well-structured and comprehensive. No changes needed.)

The above is the detailed content of Building OctoberCMS Plugins: Google Analytics. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template