Panggilan Balik
GORM leverages Callbacks
to power its core functionalities. These callbacks provide hooks for various database operations like Create
, Query
, Update
, Delete
, Row
, and Raw
, allowing for extensive customization of GORM’s behavior.
Callbacks are registered at the global *gorm.DB
level, not on a session basis. This means if you need different callback behaviors, you should initialize a separate *gorm.DB
instance.
Registering a Callback
You can register a callback for specific operations. For example, to add a custom image cropping functionality:
func cropImage(db *gorm.DB) { |
Deleting a Callback
If a callback is no longer needed, it can be removed:
// Remove the 'gorm:create' callback from Create operations |
Replacing a Callback
Callbacks with the same name can be replaced with a new function:
// Replace the 'gorm:create' callback with a new function |
Ordering Callbacks
Callbacks can be registered with specific orders to ensure they execute at the right time in the operation lifecycle.
// Register to execute before the 'gorm:create' callback |
Predefined Callbacks
GORM comes with a set of predefined callbacks that drive its standard features. It’s recommended to review these defined callbacks before creating custom plugins or additional callback functions.
Plugins
GORM’s plugin system allows for easy extensibility and customization of its core functionalities, enhancing your application’s capabilities while maintaining a modular architecture.
The Plugin
Interface
To create a plugin for GORM, you need to define a struct that implements the Plugin
interface:
type Plugin interface { |
Name
Method: Returns a unique string identifier for the plugin.Initialize
Method: Contains the logic to set up the plugin. This method is called when the plugin is registered with GORM for the first time.
Registering a Plugin
Once your plugin conforms to the Plugin
interface, you can register it with a GORM instance:
// Example of registering a plugin |
Accessing Registered Plugins
After a plugin is registered, it is stored in GORM’s configuration. You can access registered plugins via the Plugins
map:
// Access a registered plugin by its name |
Practical Example
An example of a GORM plugin is the Prometheus plugin, which integrates Prometheus monitoring with GORM:
// Registering the Prometheus plugin |
Prometheus plugin documentation provides detailed information on its implementation and usage.