search
HomeBackend DevelopmentPHP TutorialBuilding OctoberCMS Plugins: Google Analytics

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'
    ];
}

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

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'
    ];
}

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>

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');

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' %}

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'
        ]
    ];
}

Use onRender() to pass values to the page:

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

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';
}

Create models/fields.yaml:

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

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
        ]
    ];
}

Building OctoberCMS Plugins: Google Analytics

Retrieve settings in onRender():

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

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
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.