Practical Plugin System Development: Five Plugin Patterns with Complete Code Examples
Plugin mechanisms are essential for extending modern application frameworks. Instead of wading through extensive specification documents, running minimal examples provides developers with a clearer understanding of how plugins are loaded, what capabilities are injected, and how lifecycles are managed. This article walks through five common plugin development patterns, each addressing a specific real-world scenario. Complete code examples are provided, allowing developers to quickly set up, run, and validate their plugin implementations.
I. Why Learn Plugin Development Through Examples
Plugin mechanisms are the core means of extending the capabilities of modern application frameworks. Compared to reading lengthy specification documents, a runnable minimal example often helps developers establish intuitive cognition more effectively: when the framework loads plugins, what capabilities are injected, and how lifecycles are managed. This article compiles five of the most widely covered forms in plugin development, each corresponding to a real-world scenario. The code can be placed directly into a specified source directory and quickly validated via a configuration overlay layer.
Here is an overview of the five forms for easy reference:
| Example | Purpose | Key APIs |
|---|---|---|
| Example 1: Minimal Plugin | Verify environment and loading chain | apply + name |
| Example 2: Model Tool | Enable models to call your capabilities | inject: [‘tools’] + defineTool |
| Example 3: Event Listener | Insert logic at framework timings and auto-cleanup | ctx.effect |
| Example 4: Configurable | Allow users to modify plugin behavior | Config type + Schema |
| Example 5: Service Provider | Allow other plugins to call your capabilities | Service class pattern + inject |
II. The Universal Skeleton: Running All Examples in Three Steps
The five examples share the same directory structure and startup method; the only difference lies in what is registered in the source code. Once you master this skeleton, the same process can be reused for any new plugin.
Step 1: Establish the Directory
Create a plugin directory under the checked-out root directory with the following structure:
project-root/ # Check-out root (source code runtime environment must be set up)└── scratch-plugin/├── src/my-plugin.ts # All five examples are written in this file└── cordis.yml # Overlay configuration file
Step 2: Write the Overlay Configuration
Declare the plugin in cordis.yml. The id is the plugin identifier, and the name should be the absolute path to the plugin source code:
# scratch-plugin/cordis.ymlinsert:- id: demoname: '/absolute/path/to/project-root/scratch-plugin/src/my-plugin.ts'
Note: The path must be absolute. The overlay layer only contributes configuration and does not change the working directory used by the module loader to resolve paths. Relative paths will cause the module to silently fail.
Step 3: Start and Validate
Use the package manager to execute the startup command with the patch parameter (e.g., run command --patch ./scratch-plugin/cordis.yml). The expected result is that the Web interface starts normally, and the plugin node we registered appears in the plugin tree. If the environment is not yet set up, please complete the source code runtime environment preparation first.
III. Example 1: The Minimal Plugin
This is the first step in all plugin development, with only one purpose: to verify that the environment and loading chain are working. It only exposes a name and an apply function, which executes once when the plugin is loaded.
import type { Context } from 'plugin-framework'export const name = 'hello-plugin'export function apply(ctx: Context) {console.log('[hello-plugin] plugin loaded!')}
Expected result: The terminal prints [hello-plugin] plugin loaded! upon startup. This log is the “sentinel” of the entire development process—if you don’t see it, do not proceed further. Prioritize checking whether the configuration path is absolute and whether the source code is correctly compiled or loaded.
From an engineering perspective, the minimal plugin reflects two basic conventions of the plugin system: first, a plugin is a module with a name identifier; second, the framework assembles it by calling apply and passing in a context object. All subsequent capabilities are built upon these two conventions.
IV. Example 2: The Model Tool Plugin
The second pattern addresses the problem of “letting the model call your capabilities.” The plugin declares its dependency on the framework’s tools injection point via inject, and then calls defineTool to register a specific tool, including its name, description, parameter definition, and execution function.
export const name = 'tool-plugin'export function apply(ctx: Context) {ctx.inject(['tools'], (tools) => {tools.defineTool({name: 'get_current_time',description: 'Get current system time',parameters: {type: 'object',properties: {timezone: { type: 'string', description: 'Timezone, optional' }}},execute(args) {return { time: new Date().toISOString(), timezone: args.timezone ?? 'local' }}})})}
There are three main development points: the tool description must be clear enough, as the model relies on it to decide when to call the tool; the parameter structure should follow common JSON Schema conventions for easy framework validation; execute should remain idempotent and low-latency to avoid blocking the main flow.
V. Example 3: The Event Listener Plugin
The third pattern is used to insert custom logic at critical framework timings, such as request start or response end events. The core API is ctx.effect, which not only registers listeners but also handles automatic cleanup.
export const name = 'event-plugin'export function apply(ctx: Context) {ctx.effect(() => {const handler = (payload: unknown) => {console.log('[event-plugin] event received:', payload)}ctx.on('request:start', handler)// The returned cleanup function will be automatically called by the framework when the plugin is unloadedreturn () => ctx.off('request:start', handler)})}
The value of this pattern lies in lifecycle safety: developers do not need to manually unbind listeners in unload hooks. The framework ensures that resources are released synchronously when the plugin is removed, mechanically avoiding the common issue of listener leaks.
VI. Example 4: The Configurable Plugin
The fourth pattern allows plugin behavior to be adjusted by the user. The approach is to define a Config type to describe the configuration shape, while also providing a Schema to render the configuration form in the UI.
interface Config {greeting: stringverbose: boolean}export const name = 'config-plugin'export const Config: Config = { greeting: 'Hello', verbose: false }export const schema = {type: 'object',properties: {greeting: { type: 'string', default: 'Hello' },verbose: { type: 'boolean', default: false }}}export function apply(ctx: Context, config: Config) {console.log(`${config.greeting}, from config-plugin`)}
Design points: configuration items should provide reasonable defaults to ensure zero-configuration operation; the Schema and Config type fields must remain consistent to avoid discrepancies between UI display and actual parameters.
VII. Example 5: The Service Provider Plugin
The fifth pattern targets plugin collaboration: one plugin exposes capabilities in the form of a Service class, and other plugins can call it by declaring a dependency via inject.
export const name = 'service-plugin'export class MyService {query(key: string) {return `value-of-${key}`}}export function apply(ctx: Context) {ctx.provide('myService', new MyService())}
The consumer plugin uses it like this:
export const name = 'consumer-plugin'export const inject = ['myService']export function apply(ctx: Context, myService: MyService) {console.log(myService.query('demo'))}
This “provide-inject” pattern achieves loose coupling between plugins: the consumer only depends on the service contract rather than the specific implementation, meaning service implementation upgrades do not affect the caller’s code.
VIII. Conclusion and Troubleshooting Suggestions
The five patterns progress from simple to complex: the minimal plugin verifies the chain, the tool plugin integrates model capabilities, the event plugin embeds into framework timings, the configurable plugin opens up user customization, and the service plugin bridges the plugin ecosystem. In practice, it is recommended to strictly follow this order—when the minimal plugin’s log does not appear, prioritize checking the overlay path, absolute path syntax, and module compilation output. Once the chain is clear, stack capabilities one by one. After mastering this skeleton, the vast majority of plugin requirements can be categorized into one of these five forms or a combination thereof.
