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

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

问题描述

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

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 :

  • 使用继承,您不能使用多重继承,这意味着您需要将所有控制器实用程序方法放在一个地方.而且,grails 中存在一个错误,即在开发模式下无法检测基本控制器类中的任何代码更改(您需要重新启动应用程序)
  • 使用服务,您无法访问所有注入的属性,例如参数、会话、刷新...

所以我的问题是:有没有其他方法可以使用多个控制器可以访问的一些通用方法?

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.

这是一个小例子:

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

@Mixin(MyControllerCategory)
class SomethingController {

    def create = {
        printParams()
        ...
    }

    def save = {
        printParams()
    }
}

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

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