I'm assuming you already know how to create domain classes, controllers, and services. So, before you actually do that, first thing to do is to fix that in the template. Install the templates via
grails install-templates
This will populate the direct src/templates/ with three subfolders.
- artifacts
- Contains the template files for "create-*" commands; relies on dynamic scaffolding
- scaffolding
- Contains the template files for "generate-*" commands; contains everything you need
- war
- Contains the web.xml file which will control the startup/configuration of your war file (we'll come back to this later)
<%=packageName ? "package ${packageName}\n\n" : ''%>class ${className}Controller { static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
// Add the service that matches the controller ${className}Service ${domainClass.propertyName}Service def index = { redirect(action: "list", params: params) }
and use it in the methods:
def save = { def ${propertyName} = new ${className}(params) // below, use service instead of direct instance call if (${domainClass.propertyName}Service.save(flush: true)) { flash.message = "\${message(code: 'default.created.message', args: [message(code: '${domainClass.propertyName}.label', default: '${className}'), ${propertyName}.id])}" redirect(action: "show", id: ${propertyName}.id) } else { render(view: "create", model: [${propertyName}: ${propertyName}]) } }
Remember, this is the template. I'm not saying that every Controller needs a matching Service, I'm just saying that starting from that point will probably get you better separation of code in the end. Cleaner code is more maintainable. speaking as someone who lead a project where all business logic was embedded in the controllers for the first five months, well, let's just say that I wish someone had sent me a link that looked like this when we were just starting...
The Controller methods can get much more complex; we'll talk about REST later and see how to put your data out there in JSON, XML, and "whatnot".
No comments:
Post a Comment