如何在不使用继承的情况下向控制器添加常用操作? [英] How can I add common actions to controllers without using inheritance?

查看:113
本文介绍了如何在不使用继承的情况下向控制器添加常用操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不使用继承的情况下将常见操作添加到许多控制器中。我们所有的控制器都扩展了一个Abstract控制器,我想包含的功能在抽象控制器中是没有意义的。



我最初的想法是使用Mixin,但它出现了那些行为,因为它们是关闭的,不会与包含mixin的控制器混合,只有方法。

任何人都可以提出一种我可以获得的方式mixin的功能可以将控制动作添加到控制器中?

谢谢!

解决方案



例如,检查perf4j插件(文件Perf4jGrailsPlugin.groovy )。



其中,您会看到如下所示的内容:

  application.controllerClasses.each(){
addPerf4jMethods(it.clazz,log)
}

def addPerf4jMethods(artefactClass,log){
log.info添加Per4j方法: $ {artefactClass} ...


artefactClass.metaClass.withStopwatch<< {闭合可调用 - >
withStopwatch(,null,callable)
}

artefactClass.metaClass.withStopwatch<< {String tag,Closure callable - >
withStopwatch(tag,null,callable)
}
}

在上面的代码中,您遍历所有控制器并使用StopWatch添加方法,因此它们现在可以在任何地方使用。如果您只需要在某些控制器中执行此操作,则显然可以进行额外的检查。

您可以将此代码放入BootStrap.groovy,因此每次启动应用程序时都会运行该代码。

I need to add common actions to a number of my controllers without using inheritance. All our controllers extend an Abstract controller and the functionality I want to include does not make sense in the abstract controller.

My initial idea was to use a Mixin, but it appears that actions, since they are closures, are not 'mixed-in' to the controllers that include the mixin, only methods are.

Can anyone suggest a way I can get "mixin' like functionality to add actions to controllers?

thanks!

解决方案

The way to do it is to iterate over your controllers and add methods to it using metaprogramming.

For one example, check out perf4j plugin (file Perf4jGrailsPlugin.groovy).

In it, you'll see something like:

application.controllerClasses.each() {
            addPerf4jMethods(it.clazz, log)
        } 

def addPerf4jMethods(artefactClass, log) {
        log.info "Adding Per4j methods: ${artefactClass}..."


        artefactClass.metaClass.withStopwatch << { Closure callable ->
            withStopwatch("", null, callable)
        }

        artefactClass.metaClass.withStopwatch << { String tag, Closure callable ->
            withStopwatch(tag, null, callable)
        } 
}

In the code above, you are iterating through all controllers and adding methods withStopWatch, so they are now available everywhere. If you only have to do it in some controllers, you can obviously put in additional checks.

You can put this code into BootStrap.groovy, so it runs every time app starts up.

这篇关于如何在不使用继承的情况下向控制器添加常用操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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