Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a controller that extends an abstract controller in grails?

Tags:

grails

Im wondering if something like this is possbile:

abstract class AbstractController {
  def list = { 
   //default list action 
  }
}

class MyController extends AbstractController {
  def show = { 
   //show action 
  }
}

Where AbstractController is not visible on the web i.e /app/abstract/list is not accessible and where MyController has the actions list and show and is accessible on the web as /app/my/....

Anyone ever done anything like this?

like image 331
netbrain Avatar asked Jan 19 '23 19:01

netbrain


2 Answers

Try putting AbstractController into src/groovy folder.

Though, sharing functionality over Controllers might be not the best idea - it's better to move it to POGO classes or services. This question covers this issue partially: How do you share common methods in different grails controllers?

like image 111
Victor Sergienko Avatar answered Feb 15 '23 23:02

Victor Sergienko


For recent version of grails (3.x as the time of writing) it would be better to use trait instead of extending an abstract Controller or use Mixin, the later was deprecated since introducing traits in groovy v2.3, here is an example of using a trait to add a generic behaviors to your controller: 1- Create your traits in src/groovy, e.g.

import grails.web.Action

trait GenericController {

  @Action
  def test(){
    render "${params}"
  }
}

2- Implement your trait as you implement any interface:

class PersonController implements GenericController {
    /*def test(){
      render 'override the default action...'
    }*/
}

Note: traits can dynamically access all controller objects: params, response... and so on, and you still can override trait's action.

Hope this help.

like image 25
Ibrahim.H Avatar answered Feb 15 '23 22:02

Ibrahim.H