Skip to content

Modular Plugin System with Self-registering Events - #4407

Open
jekkos wants to merge 190 commits into
masterfrom
plugin-system-fresh
Open

jekkos wants to merge 190 commits into
masterfrom
plugin-system-fresh

Conversation

@jekkos

@jekkos jekkos commented Mar 6, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR implements a modular plugin system for OSPOS, based on the design discussion in #4255. Plugins are self-contained: they register their own event listeners, ship their own MVC components, their own translations, and their own logs — keeping the core free of hardcoded plugin dependencies.

Note: This description supersedes the original PR description, which described an earlier iteration of the design (e.g. Plugin_config, ExamplePlugin, Controllers/Plugins/Manage.php). See the discussion below for the evolution of the design.

Core Infrastructure

  • PluginInterface (app/Libraries/Plugins/PluginInterface.php) — contract every plugin must implement (getPluginId(), getPluginName(), getPluginDescription(), getVersion(), registerEvents(), install(), uninstall(), isEnabled(), getConfigView(), getSettings(), saveSettings()).
  • BasePlugin (app/Libraries/Plugins/BasePlugin.php) — abstract base class providing settings persistence (getSetting()/setSetting()/getSettings()/saveSettings(), JSON-encoding arrays/objects) and plugin-scoped logging (log()/logTo()).
  • PluginManager (app/Libraries/Plugins/PluginManager.php) — discovers plugin classes under app/Plugins/, validates them with is_subclass_of(PluginInterface), and registers events only for plugins that are enabled. Namespaces are loaded during pre_system (registerAllNamespaces()) so plugin handlers can register before any event fires.
  • PluginLogger (app/Libraries/Plugins/PluginLogger.php) — routes plugin log output to per-plugin log files (WRITEPATH/logs/plugins/{pluginId}.log) instead of the main application log, avoiding log spam as more plugins are installed. Exposed via the log_plugin_message() helper and the log()/logTo() methods on BasePlugin.
  • PluginConfig (app/Models/PluginConfig.php) — model backed by the ospos_plugin_config table (id, plugin_id, key, value, is_control, timestamps, with a UNIQUE KEY (plugin_id, key)). Accessors are named getValue()/setValue() (not get()/set()) to avoid conflicting with CodeIgniter\Model.
  • Migration — 20250531000000_PluginConfigTableCreate.php creates the ospos_plugin_config table (with a down() rollback) and seeds the plugins module/permission/grants.

Example Implementation

  • MailchimpPlugin (app/Plugins/MailchimpPlugin/) — the working reference plugin, refactored from the previous core Mailchimp integration. Demonstrates settings storage, a self-contained Language/{locale}/MailchimpPlugin.php translation file with a lang() helper, and safe logging (customer ID logged instead of email).

Internationalization

Plugins keep their own translations self-contained under Plugins/{PluginName}/Language/{locale}/{PluginName}.php, loaded via a lang() helper — no need to modify core app/Language/ files. See README.md in app/Plugins/ for the full pattern.

Admin UI

  • Plugins controller (app/Controllers/Plugins.php) — lists/searches plugins, and exposes enable/disable/uninstall/configure endpoints.
  • Plugin management view — lets admins enable, disable, uninstall, and configure plugins from the UI.
  • New plugins permission/module wired into ADMIN_MODULES and the menu.

Design Notes

  • Event payloads are "thin" by default — most business events (e.g. item_saved, customer_saved, customer_loaded) pass only the relevant ID(s); plugins query the model for anything else they need. This keeps events from becoming a permanent, ever-growing data contract, and lines up with a future REST API for plugins.
  • customer_deleted is a narrow exception — it must carry ['id' => $customerId, 'email' => $email] captured before deletion/anonymization, since the record (and the email specifically, when "enforce privacy" is enabled) is not reliably queryable afterward.

Documentation

  • README.md (under app/Plugins/) documents plugin structure, i18n, examples, and usage.

Related

  • Based on discussion in #4255
  • Replaces #4404 (closed due to merge conflicts)
  • Milestone: 3.5.0

@jekkos
jekkos force-pushed the plugin-system-fresh branch from 146ff4d to 48904ea Compare March 6, 2026 16:12
@objecttothis

Copy link
Copy Markdown
Member

@rmellmer can you take a look at these changes and see if they correctly finish out what you think the rest of the feature was going to look like? Can you see any potential downsides to this implementation? If not, I think we will just merge this branch so I can begin moving forward with porting plugins that are in my current production OSPOS 3.2.2 environment to this repo.

@jekkos

jekkos commented Mar 8, 2026 •

Copy link
Copy Markdown
Member Author

@objecttothis check the README.md in the plugins folder of this PR for a reference on how the system would work. The PR description is a bit outdated (after your comments)

@objecttothis objecttothis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jekkos I have a much better feel for how you have the architecture setup here and in general I like it, but I have a few questions regarding how multi-language strings, injecting plugin code into core code views and how to vet code security. See my questions below

Comment thread app/Plugins/README.md Resolved
Comment thread app/Plugins/README.md Resolved
Comment thread app/Plugins/README.md Resolved
Comment thread app/Language/en/Plugins.php Resolved
Comment thread app/Plugins/README.md Resolved
Ollama added 2 commits March 9, 2026 21:58
…events

This implements a clean plugin architecture based on PR #4255 discussion:

Core Components:
- PluginInterface: Standard contract all plugins must implement
- BasePlugin: Abstract class with common functionality
- PluginManager: Discovers and loads plugins from app/Plugins/
- Plugin_config: Model for plugin settings storage

Architecture:
- Each plugin registers its own event listeners via registerEvents()
- No hardcoded plugin dependencies in core Events.php
- Generic event triggers (item_sale, item_change, etc.) remain in core code
- Plugins can be enabled/disabled via database settings
- Clean separation: plugin orchestrators vs MVC components

Example Implementations:
- ExamplePlugin: Simple plugin demonstrating event logging
- MailchimpPlugin: Integration with Mailchimp for customer sync

Admin UI:
- Plugin management controller at Controllers/Plugins/Manage.php
- Plugin management view at Views/plugins/manage.php

Database:
- ospos_plugin_config table for plugin settings (key-value store)
- Migration creates table with timestamps

Documentation:
- Comprehensive README with architecture patterns
- Simple vs complex plugin examples
- MVC directory structure guidance
- PluginManager now recursively scans app/Plugins/ to discover plugins
- Supports both single-file plugins (MyPlugin.php) and directory plugins (MyPlugin/MyPlugin.php)
- Plugins can contain their own Models, Controllers, Views, Libraries, Helpers
- Uses PSR-4 namespacing: App\Plugins\PluginName for files, App\Plugins\PluginName\Subdir for subdirectories
- Users can install plugins by simply dropping a folder into app/Plugins/
- Updated README with comprehensive documentation on both plugin formats

This makes plugin installation much easier - just drop the plugin folder and it works.
@jekkos
jekkos force-pushed the plugin-system-fresh branch from 48904ea to bd8b4fa Compare March 9, 2026 20:58
…views

Add event-based view hook system allowing plugins to inject UI elements
into core views without modifying core files. Includes helper functions
and example CasposPlugin demonstrating the pattern.
@coderabbitai

coderabbitai Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

A plugin system framework is introduced with plugin discovery, lifecycle management, and configuration persistence backed by a database table. Hardcoded Mailchimp integration is removed from controllers and replaced with plugin-based events. Localization strings for plugin management are added across 20+ language variants.

Changes

Plugin System Architecture & Integration

Layer / File(s) Summary
Data Model & Schema
app/Models/PluginConfig.php, app/Database/Migrations/20250531000000_PluginConfigTableCreate.php, app/Database/Migrations/sqlscripts/3.4.1_PluginConfigTableCreate.sql
PluginConfig model persists plugin configuration with key/value columns. Migration creates ospos_plugin_config table and inserts plugins module, permission, and grants records linked to config permission holders.
Plugin Interface & Base Class
app/Libraries/Plugins/PluginInterface.php, app/Libraries/Plugins/BasePlugin.php
PluginInterface defines plugin contract (metadata, lifecycle, config UI, settings). BasePlugin provides concrete implementation with config persistence helpers (getSetting/setSetting), enabled-state detection, and logging utilities.
Plugin Manager & Service
app/Libraries/Plugins/PluginManager.php, app/Config/Services.php
PluginManager discovers plugins under APPPATH/Plugins, verifies PluginInterface compliance, manages lifecycle (enable/disable/uninstall), and queries plugin state. Services::pluginManager() provides shared instance with conditional initialization fallback when config table is unavailable.
Event & Configuration Wiring
app/Config/Events.php, app/Config/Autoload.php, app/Config/Constants.php
Registers PluginManager::registerAllNamespaces() on pre_system event. Autoloads Plugins controller and PluginManager library. Adds 'plugins' to ADMIN_MODULES constant and plugin helper to autoload list.
Controller & UI Layer
app/Controllers/Plugins.php, app/Helpers/plugin_helper.php, app/Helpers/tabular_helper.php
Plugins controller provides REST endpoints for plugin listing (getIndex/getSearch/getRow), lifecycle actions (postEnable/postDisable/postUninstall), and configuration (getConfig/postSaveConfig). Helper functions pluginContent/pluginContentExists trigger view events; tabular helpers generate plugin table UI.
Mailchimp Removal & Event Migration
app/Controllers/Config.php, app/Controllers/Customers.php
Removed hardcoded Mailchimp integration (decryption, API calls, list population) from Config and Customers controllers. Replaced with event triggers (customer_loaded, customer_saved, customer_deleted) to allow plugin-based extensions.
Localization
app/Language/*/Plugins.php, app/Language/*/Module.php, app/Language/*/Config.php, app/Language/*/Customers.php, app/Language/*/Sales.php
Added Plugins.php translation files across 20+ locales (ar-EG, az, bg, etc.) with UI labels for actions/status/errors. Updated Module.php to include plugins entry and removed Mailchimp entries from Config, Customers, and Sales locale files.
Documentation & Tooling
CLAUDE.md, AGENTS.md, .gitignore
Added CLAUDE.md with plugin system architecture notes, plugin discovery, event hooks, and configuration storage. Updated AGENTS.md to require PHP 8.2+ and PHPUnit 10.5.16+. Added build and cache exclusions to .gitignore.

Sequence Diagram

sequenceDiagram
    actor User
    participant Browser
    participant PluginsController
    participant PluginManager
    participant Events
    participant PluginConfig
    participant Plugin

    User->>Browser: Request /plugins/manage
    Browser->>PluginsController: GET /plugins/manage
    PluginsController->>PluginManager: getAllPlugins()
    PluginManager->>PluginConfig: Query enabled state
    PluginConfig-->>PluginManager: Plugin states
    PluginManager-->>PluginsController: Plugin list
    PluginsController-->>Browser: Render plugin table

    User->>Browser: Click "Enable" plugin
    Browser->>PluginsController: POST /plugins/enable/{pluginId}
    PluginsController->>PluginManager: enablePlugin(pluginId)
    PluginManager->>Plugin: install() [if first time]
    Plugin-->>PluginManager: Installation success
    PluginManager->>PluginConfig: Set enabled=1
    PluginConfig-->>PluginManager: State persisted
    PluginManager-->>PluginsController: Success response
    PluginsController-->>Browser: {success: true}

    Note over Events: Plugin initialization flow
    rect rgba(200, 150, 255, 0.5)
    PluginManager->>Events: registerPluginEvents()
    Events->>Plugin: registerEvents()
    Plugin->>Events: Events::on('customer_saved', ...)
    Events-->>Plugin: Event listener registered
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • objecttothis

🐰 Hop, hop, hooray! A plugin system now grows,
Where integrations bloom like spring-time flows,
No more hardcoded schemes to uphold,
Just flexible plugins, mighty and bold!

Finishing Touches

🧪 Generate unit tests (beta)

  • Create PR with unit tests
  • Commit unit tests in branch plugin-system-fresh
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Comment thread app/Plugins/README.md Resolved
@jekkos jekkos added this to the 3.6.0 milestone Mar 16, 2026
…language files

Adds documentation example showing how plugins can embed their own
language files within the plugin directory structure, keeping plugins
fully self-contained without modifying core language files.
@jekkos

jekkos commented Mar 17, 2026

Copy link
Copy Markdown
Member Author

I've updated the README.md with a new Internationalization (Language Files) section that shows how plugins can include self-contained language files.

The example demonstrates:

  • Plugin Language directory structure: Language/{locale}/CasposPlugin.php
  • Language file format (returning arrays of translations)
  • Loading language strings in plugin classes using a lang() helper
  • Using language strings in plugin views and view hooks

This keeps plugins fully self-contained - no need to modify core app/Language/ files.

See commit 6bd4bb5 for the changes.

@jekkos jekkos modified the milestones: 3.6.0, 3.5.0 Mar 17, 2026
@jekkos

This comment was marked as resolved.

@objecttothis

This comment was marked as resolved.

Comment thread app/Plugins/README.md Resolved
Comment thread app/Plugins/README.md Resolved
Comment thread app/Plugins/README.md Resolved
Comment thread app/Plugins/README.md Resolved

@objecttothis objecttothis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Take a look at my comments on the readme. Languages is now much clearer to me. Views is also cleaner this way because it limits plugin code.

Comment thread app/Plugins/README.md Resolved
@rmellmer

Copy link
Copy Markdown

@rmellmer can you take a look at these changes and see if they correctly finish out what you think the rest of the feature was going to look like? Can you see any potential downsides to this implementation? If not, I think we will just merge this branch so I can begin moving forward with porting plugins that are in my current production OSPOS 3.2.2 environment to this repo.

Sorry it took me so long to get back to looking at this. I just scanned through and looks good to me, seems in line with what I was thinking it would be.

- Add Language folder to all plugin structure examples
- Convert snake_case to camelCase for class names (PSR-12)
- Add Language folder to initial plugin structure diagram
- Add Language folder to Complex Plugin structure
- Update all namespace references to use camelCase
@jekkos

This comment was marked as resolved.

Comment thread app/Config/Events.php Resolved
Comment thread app/Config/Events.php Resolved

@objecttothis objecttothis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got through 9 of the files. I'll take a look at the rest later.

Comment thread app/Helpers/plugin_helper.php Resolved
Comment thread app/Helpers/plugin_helper.php Resolved
Comment thread app/Language/en/Plugins.php Resolved
Comment thread app/Libraries/Plugins/BasePlugin.php Resolved
- Consolidate duplicate documentation sections
- Move Internationalization section after Plugin Views
- Remove redundant Example Plugin Structure and View Hooks sections
- Fix PSR-12 brace style in plugin_helper.php
- Fix PSR-12 brace style in PluginInterface.php (remove unnecessary PHPdocs)
- Fix PSR-12 brace style in BasePlugin.php (remove unnecessary PHPdocs)
- Use log_message() instead of error_log() in migration
- Add IF NOT EXISTS to plugin_config table creation for resilience
- Convert snake_case to camelCase for class names throughout docs
@jekkos

This comment was marked as resolved.

Add getExportDataBulk() to Item model for plugin use.

- Fetches item_id, item_number, name, description, unit_price,
  and pic_filename for multiple item IDs in single query
- Returns results keyed by item_id for easy lookup
- Guards against empty input array

Signed-off-by: objecttothis <[email protected]>
Add explicit guidance in AGENTS.md and app/Plugins/README.md
stating core code must never reference a specific plugin.

- Clarify no plugin name/path may appear in composer.json,
  package.json, app/Config/*, or other core files
- State plugins resolve solely via PSR-4 autoloading and
  PluginManager runtime auto-discovery
- Note installing/removing a plugin must never require
  editing files outside app/Plugins/<PluginName>/

Signed-off-by: objecttothis <[email protected]>
objecttothis and others added 11 commits October 26, 2026 17:31
Resolve language file conflicts: take master's translations, strip
MailChimp phrases (MailChimp is now a plugin instead of core), and
retain plugin-system additions (plugins/plugins_configuration keys).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Remove Georgian (ka) locale entries for mailchimp integration
strings that are no longer referenced in the app.

- app/Language/ka/Config.php: drop mailchimp_* config labels
- app/Language/ka/Customers.php: drop mailchimp_activity_*,
  mailchimp_info, mailchimp_member_rating, mailchimp_status,
  mailchimp_vip entries

Signed-off-by: objecttothis <[email protected]>
MailchimpConnector called curl_close($ch) immediately after
curl_exec, before checking curl_errno/curl_error on failure.
Closing the handle early invalidates it for any subsequent
curl_getinfo/curl_error calls that rely on the handle.

- Drop curl_close call in MailchimpConnector.php so the handle
  stays valid through error inspection; connector is responsible
  for closing it later where appropriate

Signed-off-by: objecttothis <[email protected]>
…m-fresh

# Conflicts:
#	app/Controllers/Items.php
#	app/Models/Item.php
#	app/Models/Stock_location.php
#	app/Views/items/form_count_details.php
Align method naming with codebase conventions by converting
snake_case model/controller methods to camelCase.

- Employee::get_info -> getInfo, updated in Employees and Sales
  controllers
- Sale::get_info -> getInfo, updated in Sales controller
- Item::get_multiple_info -> getMultipleInfo, updated in ItemTest
- Customers import: fix loop counter bug where $i was reused/
  reassigned inconsistently, renamed to $rowNumber with ++$rowNumber
  pre-increment for clarity
- Sales::save_row_customer_data: fix variable typo $sale_id ->
  $saleId to match surrounding naming and avoid undefined variable

Signed-off-by: objecttothis <[email protected]>
Rename snake_case locals (cash_adjustment, amount_tendered, sale_id,
sale_info) to camelCase (cashAdjustment, amountTendered, saleId,
saleInfo) in Sales::processPayment cash-adjustment branch. Aligns
with surrounding camelCase usage (amountTendered, saleInfo already
referenced below in the same block) and fixes undefined-variable
bug caused by naming mismatch.

Signed-off-by: objecttothis <[email protected]>
- Fix broken array/method chain in debug-js task where a stray
  string concatenation left `.pipe(rev()).pipe(gulp.dest(...))`
  embedded inside the file list array instead of after it
- Close file list array properly after plugin_data_helper.js entry
  so the pipeline methods run once, after the array is complete

Signed-off-by: objecttothis <[email protected]>
Map plugin.svg source icon to plugins.svg in MENUBAR_ICONS list
so build pipeline generates correct icon for plugins menu item.

Signed-off-by: objecttothis <[email protected]>
- composer.json: exclude Plugins/*/Migrations from classmap,
  matching existing Database/Migrations exclusion so plugin
  migration classes aren't autoloaded directly
- composer.json: widen platform PHP requirement from ^8.2 to
  allow patch ranges across 8.2/8.3/8.4 (>=8.2.35 <8.3 ||
  >=8.3.36 <8.4 || >=8.4.27), likely to exclude vulnerable
  patch versions
- composer.lock: regenerate content-hash to match composer.json
  changes

Signed-off-by: objecttothis <[email protected]>
- Add allowScripts entry for [email protected] in package.json so
  its postinstall lifecycle script is permitted during install

Signed-off-by: objecttothis <[email protected]>
… table

- Rename core migration 20260627000000_PluginMigrationsTableCreate to
  20261026000000_PluginConfigTableCreate, merging plugin_migrations
  table creation into the same SQL script as plugin_config and adding
  a startup log message; down() now drops both tables.
- Consolidate the plugin_migrations CREATE TABLE statement into
  3.5.0_PluginConfigTableCreate.sql and remove the now-redundant
  3.5.1_PluginMigrationsTableCreate.sql script.
- Update app/Plugins/README.md reference to the renamed migration
  class.
- Add WhatsAppPlugin migration CreateWhatsAppMessagesTable to create
  the whatsapp_messages conversation log table (utf8mb4, unique
  wa_message_id to dedupe webhook redelivery); dropped explicitly by
  WhatsAppPlugin::uninstall() instead of a down() method.

Signed-off-by: objecttothis <[email protected]>
…m-fresh

# Conflicts:
#	app/Controllers/Customers.php
#	app/Models/Item.php
objecttothis and others added 3 commits November 6, 2026 13:43
…m-fresh

Resolve language-file conflicts by taking master's English-removal
cleanup across non-English locales, while stripping the MailChimp
keys master reintroduced (already moved to MailchimpPlugin on this
branch) and reapplying this branch's plugins/integrations rename and
new Module.php plugins keys where master lacked them.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Remove 'integrations' and 'integrations_configuration' (and
'plugins'/'plugins_configuration' in ckb) entries from Config.php
across all language files under app/Language/*.

- Dead keys no longer referenced in UI, dropped repo-wide for
  consistency across locales (ar-EG, ar-LB, az, bg, bs, ckb, cs,
  da, de-CH, de-DE, el, en-GB, en, es-ES, es-MX, fa, fr, and others)
- Keeps all language Config.php files structurally in sync

Signed-off-by: objecttothis <[email protected]>
- Add static getParsedFile() helper that caches include-based
  file parses per file path
- Replace repeated `include $file` calls in
  testLanguageFile_ParsesToArray, key-matching, and key-sorting
  tests with calls to the cached helper
- Avoid redundant file includes/parsing when the same language
  file is loaded across multiple test methods, speeding up the
  test suite

Signed-off-by: objecttothis <[email protected]>
…m-fresh

# Conflicts:
#	app/Config/Filters.php

This branch had an error being deployed

1 failed (outdated) deployment
staging — 5cd66d76 Deployed Jun 15, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Third-party integration standard architecture Plugin Infrastructure

4 participants