简体   繁体   中英

Reusable Grails controller helper methods

How to create reusable Grails controller helper methods which can be used in many controllers?

Right not I have few private methods in one controller. I want to share them with other controllers.

I would like have access to params , redirect etc.

The correct way to share code between controllers is to abstract the logic into a service. See

http://grails.org/doc/latest/guide/services.html

Note that if the service is not required to be transactional you should mark it as such.

If however you have web related logic (such as writing templates or markup to the output stream) then you can also use tag libraries to share logic, as tags can be invoked from controllers. See:

http://grails.org/doc/latest/guide/theWebLayer.html#tagsAsMethodCalls

You can use Mixins to you put all your common code:

// File: src/groovy/com/example/MyMixin.groovy
class MyMixin {
    private render401Error() {
        response.status = 401
        def map = [:]
        map.message = "Authentication failed"

        render map as JSON
    }
}

Now in a controller you can do something like this:

// File: grails-app/controller/com/example/OneController.groovy
@Mixin(MyMixin)
class OneController {
    public someAction() {
        if (!user.isAuthenticated) {
            // Here we're using the method from the mixin
            return render401Error()
        }
    }
}

Just one final advice: Mixins are applied during runtime so there is a little overhead.

The simplest answer is to create a class in src with a bunch of static methods and pass everything around as parameters, see: http://grails.org/doc/2.3.8/guide/single.html#conventionOverConfiguration

...or else create a controller base class that all other controllers extend from?

That said, I wonder if you are actually looking for scoped services? See http://ldaley.com/post/436635056/scoped-services-proxies-in-grails .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM