Creating Singleton DB Instance with Methods
The original code provided contains a singleton implementation, but lacks methods that can be called on the singleton instance. This article demonstrates how to augment the provided singleton with methods and addresses questions related to error handling.
Revised Singleton Implementation with Methods
In the updated code, we define an exported interface Manager with the desired methods (AddArticle in this case). We then create an unexported implementing type manager. A global variable Mgr of the interface type is initialized in a package init() function, ensuring it is instantiated only once.
<code class="go">package dbprovider import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "rest/article" "log" ) type Manager interface { AddArticle(article *article.Article) error } type manager struct { db *gorm.DB } var Mgr Manager // Global variable of the interface type func init() { db, err := gorm.Open("sqlite3", "../articles.db") if err != nil { log.Fatal("Failed to initialize database:", err) } Mgr = &manager{db: db} } func (mgr *manager) AddArticle(article *article.Article) error { if err := mgr.db.Create(article).Error; err != nil { return err } return nil }</code>
Using the Singleton
The Mgr instance can now be used to add articles to the database:
<code class="go">import "dbprovider" if err := dbprovider.Mgr.AddArticle(someArticle); err != nil { // Handle error }</code>
Error Handling
To catch and return exceptions from gorm.Create(), we check the error returned by gorm.Create().Error. If an error occurred, it is returned; otherwise, nil is returned.
Conclusion
This revised implementation creates a singleton DB instance with methods that can be called on the singleton reference. It also demonstrates how to handle exceptions from gorm.Create().
The above is the detailed content of How to Create a Singleton DB Instance with Methods and Error Handling?. For more information, please follow other related articles on the PHP Chinese website!