How do you share common methods in different grails controllers?

后端 未结 5 1650
南笙
南笙 2020-12-13 01:39

Currently when I need to share a method like processParams(params) between different controllers, I use either inheritance or services. Both solution has some

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 02:06

    One option I like is to write the common methods as a category, then mix it into the controllers as necessary. It gives a lot more flexibility than inheritance, has access to stuff like params, and the code is simple and understandable.

    Here's a tiny example:

    @Category(Object)
    class MyControllerCategory {
        def printParams() {
            println params
        }
    }
    
    @Mixin(MyControllerCategory)
    class SomethingController {
    
        def create = {
            printParams()
            ...
        }
    
        def save = {
            printParams()
        }
    }
    

提交回复
热议问题