你如何在不同的grails控制器中分享常见的方法? [英] How do you share common methods in different grails controllers?

查看:92
本文介绍了你如何在不同的grails控制器中分享常见的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,当我需要在不同控制器之间共享像 processParams(params)这样的方法时,我使用继承或服务。
这两个解决方案都有一些不便:


  • 使用继承,您不能使用多重继承,这意味着您需要拥有所有的控制器实用方法集中在一个地方此外,在开发模式下,Grails中没有检测到基本控制器类中的任何代码更改的错误(您需要重新启动应用程序)。
  • 使用服务,您没有访问所有注入的属性,如params,session,flush ...



所以我的问题是:还有其他方式可以使用常见的方法可以访问多个控制器吗?

解决方案

我喜欢的一种选择是将常用方法编写为一个类别,然后将其混合必要的控制器。它比继承提供了更多的灵活性,可以访问像params这样的东西,代码简单易懂。



这是一个小例子:

  @Category(Object)
class MyControllerCategory {
def printParams(){
println params
}


@Mixin(MyControllerCategory)
类SomethingController {

def create = {
printParams()
.. 。
}

def save = {
printParams()
}
}


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

  • With inheritance, you cannot use multiple inheritance which means that you need to have all of your controller utility methods in one place. And also, there is a bug in grails that does not detect any code changes in Base Controller classes in development mode (you need to restart the app)
  • With services, you don't have access to all injected properties like params, session, flush...

So my question is : is there any other way to use some common methods accessible for multiple controllers ?

解决方案

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()
    }
}

这篇关于你如何在不同的grails控制器中分享常见的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆