Callbacks
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.
回调是在全局的 *gorm.DB
级别的,不是在session级别的。 This means if you need different callback behaviors, you should initialize a separate *gorm.DB
instance.
注册 Callback
您可以为特定操作注册回调。 例如,要添加自定义图像裁剪功能:
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
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.