Defining a Grails 3.0 plugin domain class to be extendable

564 views Asked by At

When developing a Grails 3.0 plugin:

  1. How should a domain be defined so that it can be extended by the application using the plugin?
  2. How does the plugin reference instances of the extended class?

As an example, a security plugin could have classes such as:

User.groovy

package com.example.plugins.security

class User {

   String  email
   String  hash
   Boolean enabled = true

}

SecurityService.groovy

package com.example.plugins.security

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder

class SecurityService {

   def authenticate(String email, String password) {
      def user = User.findByEmail(email)  //instance of BookstoreUser???
      def encoder = new BCryptPasswordEncoder()
      return user && encoder.matches(password, user.hash) ? user : null
      }

}

The application would have a domain such as:

grails-app/domain/com/example/bookstore/BookstoreUser.groovy

package org.example.bookstore

import org.bson.types.ObjectId
import org.example.plugins.security.User

class BookstoreUser extends User {

   ObjectId id
   String   firstName
   String   lastName

   static mapWith = "mongo"

}

The rest of the code is at:
https://github.com/center-key/bookstore

1

There are 1 answers

6
Jeff Scott Brown On

How should a domain be defined so that it can be extended by the application using the plugin?

The same way you would define any other domain class. Declare the Groovy source file under grails-app/domain/.

How does the plugin reference instances of the extended class?

The code that you show in your question would work fine.

package com.example.plugins.security

class SecurityService {

   def disableUser(User user) {  //the instance should be a BookstoreUser
          user.enabled = false
          user.save()
      }
}

If an application writes a class like BookstoreUser that extends your User class, an instance of BookstoreUser can be passed into your disableUser method and that method will behave as you probably expect it should. The method will set the enabled property to false and will then save the updated instance.