Repository navigation
Feature plugins framework - #4255
objecttothis wants to merge 9 commits into
Conversation
- Add custom events for item changes, sales, returns, and inventory. - Add custom events for item and customer csv imports. Signed-off-by: objecttothis <[email protected]>
- Add custom events for item changes, sales, returns, and inventory. - Add custom events for item and customer csv imports. - Refactor variable names for PSR-12 compliance. - Refactor function names for PSR-12 compliance. - Moved retrieving of $employeeId to actually where it's going to be used for readability. - Added trigger point for item save. - Added trigger point for item delete. - Added debug logging for item_change event trigger. - Added itemId to be sent in the item_change event. Signed-off-by: objecttothis <[email protected]>
|
|
||
| $method = new Method(); | ||
| Events::on('pre_controller', [$method, 'validate_method']); | ||
|
|
There was a problem hiding this comment.
@jekkos can you think of other events that we want to include?
There was a problem hiding this comment.
Hi thanks for this first draft @objecttothis . Now I do believe the approach is not completely what I had in mind. To achieve the decoupling we need to fire the events from our application code and within the correct context.
Eg when a sale is registered at the very end, we should call Events::trigger('sale_completed', $sale_id, $sale_info);. Any plugin's code will then be called after they register their functionality the way you show it here. So basically this file is not really required, the code will be peppered with trigger events logic and that will call the plugin code without having a direct dependency
There was a problem hiding this comment.
@jekkos I don't understand. This file is where the definition of the various event triggers are made so if I don't have them here, we won't be able pepper the code with the event triggers which kick off the third party integrations. Can you help me understand what you mean by this file not being needed? Per the ci4 documentation, I believe it's needed for events.
There was a problem hiding this comment.
@jekkos here is the documentation I was referring to (https://codeigniter.com/user_guide/extending/events.html#publishing-your-own-events).
So, for example here we would call 3rd party integrations so that only the trigger is what is in the code
Events::on('item_sale', static function (array $saleData): void {
exampleIntegrationUploadToWebsite($saleData);
exampleIntegrationSendToGovernmentPrinter($saleData);
exampleIntegrationUpdateMarketPlace($saleData);
log_message('debug', "Item sale event triggered on sale ID: {$saleData['sale_id_num']}");
});
These examples are just fillers, but if we don't put these trigger definitions in the Events file, I don't really understand how you intend for them to be called without putting them in the code directly which will make it much messier than just the event::trigger() code.
There was a problem hiding this comment.
We need to setup these callbacks somewhere that is correct but it should be done per integration. So we should agree on a convention for setting up the callback without touching code in. the main module. In this case every integration can have its own Events.php that registers whatever callback it wants. So those should be distributed with the integration code and ideally not touch any core ospos controller
There was a problem hiding this comment.
Ok so for this concrete example, it might look like the code below, which will not require any imports or direct dependency on any plugin package from this file.
Events::on('item_sale', static function (array $saleData): void {
// ideally we store callbacks in a map per event, then retrieve the list for this event
foreach (callback in callbacks) {
// invoke callback in a dynamic way (and hopefully number of args match, have to check how it can be done in php)
}
log_message('debug', "Item sale event triggered on sale ID: {$saleData['sale_id_num']}");
});
| echo json_encode(['success' => true, 'message' => $message, 'id' => $itemId]); | ||
|
|
||
| echo json_encode(['success' => true, 'message' => $message, 'id' => $item_id]); | ||
| Events::trigger('item_change', $itemId); |
There was a problem hiding this comment.
@jekkos this is an example of the trigger. It's nice and clean because none of the plugin code gets injected here. Just these triggers.
| * This event triggered when an item is changed. This can be an item create, update or delete. | ||
| * Plugin functionality is triggered here. | ||
| */ | ||
| Events::on('item_change', static function (int $itemId): void { |
There was a problem hiding this comment.
$itemId is an example of being able to pass data from the trigger point. So for example, when someone changes an item, it sends the itemId that was changed here and, let's say a plugin decides to make an API call to a website to update the item on the website. In this static function we could call the controller method of the plugin to make the API call. Easy peasy. Plugin Controller code is in it's own space.
|
The refactoring of variable and function names to camelCase are variables and functions in sections of code I am modifying and are for PSR-12 compliance. |
- Place trigger in Sale Controller. - Refactor variable names to camelCase for PSR-12 compliance - Refactor function names to camelCase for PSR-12 compliance - Minor readability refactoring of if/else to ternary notation - Removed hungarian notation Signed-off-by: objecttothis <[email protected]>
- Refactor function names to camelCase for PSR-12 compliance Signed-off-by: objecttothis <[email protected]>
- This fix properly creates Primary Keys on both MariaDB and MySQL Signed-off-by: objecttothis <[email protected]>
- Migration to create the table in the database - Removed unneeded using statements Signed-off-by: objecttothis <[email protected]>
|
@jekkos we need to make a few design decisions with this.
The question is how to do 1 and 3 so that weblate does not flip out. Also, do you have any objection to 2? |
- Renamed view from integrations_config to plugins_config.php - Added Plugin - Added todo in the code for refactoring - Refactored config.php strings - Moved mailchimp strings to Plugins.php for en. We will need to do this for all the languages perhaps to retain current translations. - Refactored view to use plugins naming Signed-off-by: objecttothis <[email protected]>
- Renamed view from integrations_config to plugins_config.php - Added Plugin - Added todo in the code for refactoring - Refactored config.php strings - Moved mailchimp strings to Plugins.php for en. We will need to do this for all the languages perhaps to retain current translations. - Refactored view to use plugins naming - Refactored Savefunction name - Refactored view identifiers to be more generic - Added Plugins folders in Controllers, Models and Views - Refactored check_encryption function for PSR-12 compliance Signed-off-by: objecttothis <[email protected]>
|
I don't know why the following is happening when trying to get a migration. |
This happened to me the other day but it was because I tried to run a migration when my .env file had already been modified by the upgrade to CI4 which converts encryption from CI3 encryption to CI4 in the database and lengthens the encryption key. I've thought about making it more robust, but really it's a use case that should only be encountered during testing. Are you migrating a clean or pre-existing database? before running the migration did you have a CI3 key or was it a CI4 key? |
|
I really don't know. I use what db happens to be available at the time. Probably multiple pre-existing ci3 databases. |
|
|
||
| $method = new Method(); | ||
| Events::on('pre_controller', [$method, 'validate_method']); | ||
|
|
There was a problem hiding this comment.
Hi thanks for this first draft @objecttothis . Now I do believe the approach is not completely what I had in mind. To achieve the decoupling we need to fire the events from our application code and within the correct context.
Eg when a sale is registered at the very end, we should call Events::trigger('sale_completed', $sale_id, $sale_info);. Any plugin's code will then be called after they register their functionality the way you show it here. So basically this file is not really required, the code will be peppered with trigger events logic and that will call the plugin code without having a direct dependency
| } else { | ||
| $data['barcode'] = $this->barcode_lib->generate_receipt_barcode($data['sale_id']); | ||
| $data['barcode'] = $this->barcode_lib->generateReceiptBarcode($data['sale_id']); | ||
| Events::trigger('item_sale', $data); |
There was a problem hiding this comment.
@jekkos I think you're trying to avoid integrations business logic from getting mixed together in the Events.php file by saying that each integration should have it's own Events.php. I 100% agree that the business logic for each integration needs to be separated from the OSPOS code and from each other.
Here's the problem. If I understand what you're saying we should do, by each integration having it's own Events.php, that means the OSPOS code will have a significant number of Events::trigger() calls. I have at least 5 integrations planned alone and I'm sure others will have some as well. I can see a dozen or more of these Events::trigger() calls clustered throughout the code.
Here is what I think we should do:
- Have one Events.php defining these event listener callback functions.
- DO NOT do integration business logic in these callback functions, but instead the callback functions would contain a single call for each integration's codespace so that each integration does it's business logic in it's own space.
- Have one trigger call per area in the OSPOS code that integrations need and pass all the data that is needed for any integrations that want it.
This way it prevents the code from being peppered with trigger calls but it also keeps each integration in it's own space. Am I misunderstanding something about what you're wanting to do?
There was a problem hiding this comment.
I'll try to explain why I think a shared Events.php might have some drawbacks
Primary reason to separate the callback registration from the core OSPOS logic is modularity. If we install a plugin then it should leave the core OSPOS files untouched, otherwise there will be too many combinations of plugin activations that make up the common Events.php file. A plugin should be able to describe what callbacks it wants to register and ideally we do this through a common interface that is implemented. This common interface could be an Events.php file that is supplied by every plugin by default
Uninstalling a plugin should come down to removal of the integration code from the plugins folder. Beside that we could also support deactivation which would rely on a database flag that disables a specific plugin's callback registration.
If we have a common Events.php with direct dependencies on specific plugin code then the deactivation feature will be harder to implement. as every callback registration will need to wrapped with checks to see if the plugin is active or not.
There was a problem hiding this comment.
And then there is also a versioning aspect. An integration needs to track compatibility with the core OSPOS logic, so we should have some logic that checks the callback function signatures and whether they align with how the trigger invokes them. So I do agree that there might need to be some cerntral place in the core logic where we define just the function types, so they can be inspected and any integration that does not honor the typing can be disabled as it's incompatible or not up to date. It will help us loading plugins that are in outdated or broken state.
So we could still centralize just the callback function signature. The callback registration can also be done in a dynamic way after validating the plugin provided signatures. Then we only have generic code in the core OSPOS domain and all implementation stays in the plugin source itself
There was a problem hiding this comment.
I tried to clarify this a bit by editing the code example you wrote, it might look quite similar except that there should be no imports of external plugin classes in the common shared Events.php
There was a problem hiding this comment.
Primary reason to separate the callback registration from the core OSPOS logic is modularity. If we install a plugin then it should leave the core OSPOS files untouched, otherwise there will be too many combinations of plugin activations that make up the common Events.php file.
But won't any new plugins have to add in Events::trigger() entries into the core OSPOS logic if we do what you are suggesting? Maybe you can clarify what you mean by untouched, because the only way I can think of to keep integrations from touching core OSPOS logic is by making them call their handling function in an Event listener then the trigger is placed and not changed regardless of which integrations are present. Here is an example of what I mean
This is what I'm proposing in a single Events.php
/**
* This event triggered when an item sale occurs.
* Plugin functionality is triggered here.
*/
Events::on('item_sale', static function (array $saleData): void {
Wolt::itemUpdate($saleData); //Integration logic not handled here. These functions contain their logic to their own classes, models, helpers, etc.
BirMarket::itemUpdate($saleData);
CLCDESQ::productPush($saleData);
CASPOS::sale($saleData);
WhatsApp::itemUpdate($saleData);
log_message('debug', "Item sale event triggered on sale ID: {$saleData['sale_id_num']}");
}); Events::trigger('item_sale', $data); //This remains untouched regardless of the integrations.If I understand the route you are suggesting, then the OSPOS triggers get touched with every new integration
WoltEvents::trigger('item_update', $data); //These would need to be added and removed throughout the code with each new plugin.
BirMarketEvents::trigger('item_update', $data);
CLCDESQEvents::trigger('product_push', $data);
WhatsAppEvents::trigger('item_update', $data);
CASPOSEvents::trigger('sale', $data);A plugin should be able to describe what callbacks it wants to register and ideally we do this through a common interface that is implemented. This common interface could be an Events.php file that is supplied by every plugin by default
Can you clarify? By common interface, do you mean standardized or do you mean singular?
Uninstalling a plugin should come down to removal of the integration code from the plugins folder. Beside that we could also support deactivation which would rely on a database flag that disables a specific plugin's callback registration. If we have a common Events.php with direct dependencies on specific plugin code then the deactivation feature will be harder to implement. as every callback registration will need to wrapped with checks to see if the plugin is active or not.
OK, this brings up an interesting topic for discussion with a few different questions. There is the issue of installation and a separate issue of activation & deactivation.
Installation (completely modular)
This is sort of the route that CMSs like WordPress take. There are a few different approaches we can take. One approach is a completely modular one in which the integration plugin code is not in the OSPOS repository and these plugins need to be developed externally, installed either manually or through some sort of installer script. This route requires a significant amount of modularity and I'm not really sure how we would expect developers to inject their trigger calls into OSPOS core code during installation.
Installation (always installed)
What I thought we were doing is creating a separate codespace (app/Controllers/Plugins, app/Models/Plugins, app/Helpers/Plugins and app/Libraries/Plugins) and confining Integration code to their own clearly marked classes and files, but that code living in the OSPOS repository so that we could maintain some amount of control to prevent egregious vulnerabilities, but still maintain separation of concerns.
Activation & Deactivation
I had always intended on handling activation/deactivation of plugins through boolean values in the ospos_plugin_config table we talked about adding. So at that point my example becomes:
/**
* This event triggered when an item sale occurs.
* Plugin functionality is triggered here.
*/
Events::on('item_sale', static function (array $saleData): void {
$woltIsActive && Wolt::itemUpdate($saleData);
$birMarketIsActive && BirMarket::itemUpdate($saleData);
$clcdesqIsActive && CLCDESQ::productPush($saleData);
$casposIsActive && CASPOS::sale($saleData);
$whatsAppIsActive && WhatsApp::itemUpdate($saleData);
log_message('debug', "Item sale event triggered on sale ID: {$saleData['sale_id_num']}");
});No matter how we do it the control and setting of which plugins are active will need to be tackled, but doing it in one place is better.
Plugin configuration
@jekkos we also need to think about how configuration of plugins happens. I thought we were going to be creating partial views in app/Views/configs/plugins where each would be the configuration for that plugin and the values would be stored in the ospos_plugin_config table
There was a problem hiding this comment.
I'm finally getting around to looking at this again. Sounds like it might be simpler to have each plugin register it's own events that the plugin cares about for itself?:
// In Mailchimp plugin
Events::on('item_sale', static function (array $saleData): void { // do something with mailchimp });
// In WhatsApp plugin
Events::on('item_sale', static function (array $saleData): void { // do something with whatsapp });
// In CASPOS plugin
Events::on('item_sale', static function (array $saleData): void { // do something with CASPOS });
Each plugin could have a register function to register all its events:
// In each plugin's Plugin.php
public function register(): void
{
Events::on('item_sale', [$this->getEventHandler('CustomerHandler'), 'onSale']);
}
Then somewhere in OSPOS we'd do:
foreach ($activePlugins as $pluginName => $plugin) {
$plugin->register(); // Each plugin registers its own events
}
There was a problem hiding this comment.
@rmelleem exactly that way you keep the code in the plugin and separate it from the main application logic
There was a problem hiding this comment.
@rmellmer and @jekkos the code snippet does provide an elegant solution for declaring and registering independent events in its own code however one thing isn't clear to me. How does this solution prevent the code from being absolutely peppered with event triggers? It's not unreasonable for us to assume that there could be upwards of 15-20 plugins and each could have 1-5 event types that it cares about. I'm imagining the code littered with event::trigger() calls.
The option I think you guys are proposing might look like:
- Per-plugin event triggers inside OSPOS code space (x plugins * 1-5 events * 1-3 triggers per event type) > for each to register active trigger types > well contained event registers inside the plugin codespace
The option we started with might look like:
- generic event triggers inside OSPOS code space at the points needed by one or more plugins including all data needed by plugins > for each event function rather than have that be a mess of plugins doing business logic to have the plugin make a single call to it's code space with relevant data it cares about > well contained plugin business logic code in its own codespace.
Am I missing something here with my fear about the number of event triggers that will end up in the code space?
There was a problem hiding this comment.
What I was thinking was more along the lines of this:
- generic event triggers inside OSPOS code space at the points needed by one or more plugins including all data needed by plugins > for each to register active triggers for each enabled plugin > well contained event registers inside the plugin codespace
Like you had above, this is what the internal OSPOS trigger would still look like:
Events::trigger('item_sale', $data); //This remains untouched regardless of the integrations.
The only difference is instead of a single Events.php file listening to that item_sale trigger, and having to know what every plugin wants to do with that, we have each plugin that wants to listen to the item_sale trigger set that up that listener on its own, and then it can do whatever it wants to with it.
Plugins would only be allowed to use the generic triggers that we define in the OSPOS code space. Each plugin then listens to whatever generic event triggers they need in their register function.
Hopefully that makes sense. I can hop on a call or make a whiteboard drawing if that would be more helpful to describe the idea.
There was a problem hiding this comment.
I think I understand what you're saying and I like that implementation.
…events - Add PluginInterface for standardized plugin contract - Add BasePlugin abstract class with common functionality - Add PluginManager for discovering and loading plugins - Add PluginConfigModel for plugin settings storage - Refactor Events.php to use PluginManager at post_system - Add ExamplePlugin demonstrating the plugin system - Add MailchimpPlugin as integration example - Add plugin management controller and views - Update plugin_config table migration with timestamps - Add comprehensive README documentation This implementation follows the design discussed in PR #4255: - Each plugin registers its own event listeners - No hardcoded plugin calls in core code - Plugins are modular and self-contained - Generic triggers remain in core code - Plugin enable/disable via database settings
…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
…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
…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

This framework provides the custom events which, when triggered, can be used by plugins to make API calls or other read-only data manipulations.