Skip to content
GeorgeNava edited this page Jul 16, 2011 · 3 revisions

Design your models

Once you need to store more data, complexity starts to grow so it is a good idea to organize your models and data access methods in a package that we will name 'models' for easy reference. Just create a folder 'models', next to 'app' and 'db' in your application folder and edit a new file named 'models.go' where you will put all your entities and methods like:

package models

import(
    "app"
    "db"
)

type Customer struct{
    ID      string
    Created int64
    Name    string
    Phone   string
    Email   string
}


// Gets a list of the latest N customers added
func GetCustomers(ctx app.Context, n int) []Customer {
  DB   := db.New(ctx.Request)
  recs := make([]Customer, 0, n)
  qry  := DB.Query("Customer").Order("-Created").Limit(n)
  ok   := DB.Select(qry, &recs)
  if !ok { return nil }
  return recs
}


// Gets a customer record by id
func GetCustomer(ctx app.Context, id string) (Customer,bool) {
  DB  := db.New(ctx.Request)
  rec := Customer{}
  ok  := DB.Get(id, &rec)
  return rec,ok
}

// Inserts a new customer record
func NewCustomer(ctx app.Context, data Customer) Customer {
  DB  := db.New(ctx.Request)
  rec := Customer{
    ID      : data.ID,
    Created : DB.Now(),
    Name    : data.Name,
    Phone   : data.Phone,
    Email   : data.Email,
  }
  DB.Put(data.ID, &rec)
  return rec
}

// Updates a customer record
func SaveCustomer(ctx app.Context, data Customer) Customer {
  DB := db.New(ctx.Request)
  rec,ok := GetCustomer(ctx, data.ID)
  if ok {
     rec.Name   = data.Name
     rec.Phone  = data.Phone
     rec.Email  = data.Email
     DB.Put(data.ID, &rec)
  }
  return rec
}

// Deletes a customer record by ID
func DeleteCustomer(ctx app.Context, id string) bool {
  DB := db.New(ctx.Request)
  ok := DB.Delete("Customer",id)
  return ok
}

Then, from anywhere in your app, you just call models.getCustomers(ctx,10) to get the latest ten customers added to your database. Easy huh?

Tip: It is good practice to encapsulate all entity methods (get, new, save, delete) in a package instead of dealing with complex code that can cause data integrity problems and bugs everywhere. You can attach the methods to the type too, if that is your style, so you can create a Customer{} and then call Customer.Save() keeping the code clean.

Clone this wiki locally