我分别使用 Play-Slick 2.5.x 和 3.1.x 版本。我使用 Slick 的代码生成器并从现有数据库中生成 Slick 模型。实际上,我很害羞地承认我是 DB 设计驱动而不是类设计驱动的。
这是初始设置:
- 下生成的 Slick 模型
generated.Tables._
- 通用 Slick dao 实现
- 建立在 Generic Slick dao 之上的服务层
这些是我暂时称为“可插入服务”的模式背后的力量,因为它允许将服务层功能插入模型:
- Play 的控制器和视图必须只能看到 Service 层(而不是 Dao 的),例如
UserService
- 生成的模型,例如
UserRow
,预期遵守业务层接口,例如 Deadbolt-2 的主题,但不直接实现它。为了能够实现它,需要“太多”,例如UserRow
模型类型,UserDao
以及潜在的一些业务上下文。 - 一些
UserService
方法自然适用于模型UserRow
实例,例如loggedUser.roles
或loggedUser.changePassword
因此我有:
generated.Tables.scala
光滑的模型类:
case class UserRow(id: Long, username: String, firstName: String,
lastName : String, ...) extends EntityAutoInc[Long, UserRow]
dao.UserDao.scala
特定于 User 模型的 Dao 扩展和自定义:
@Singleton
class UserDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends GenericDaoAutoIncImpl[User, UserRow, Long] (dbConfigProvider, User) {
//------------------------------------------------------------------------
def roles(user: UserRow) : Future[Seq[Role]] = {
val action = (for {
role <- SecurityRole
userRole <- UserSecurityRole if role.id === userRole.securityRoleId
user <- User if userRole.userId === user.id
} yield role).result
db.run(action)
}
}
services.UserService.scala
为 Play 应用程序的其余部分提供所有用户操作的服务:
@Singleton
class UserService @Inject()(auth : PlayAuthenticate, userDao: UserDao) {
// implicitly executes a DBIO and waits indefinitely for
// the Future to complete
import utils.DbExecutionUtils._
//------------------------------------------------------------------------
// Deadbolt-2 Subject implementation expects a List[Role] type
def roles(user: UserRow) : List[Role] = {
val roles = userDao.roles(user)
roles.toList
}
}
services.PluggableUserService.scala
最后是动态地将服务实现附加到模型类型的实际“可插入”模式:
trait PluggableUserService extends be.objectify.deadbolt.scala.models.Subject {
override def roles: List[Role]
}
object PluggableUserService {
implicit class toPluggable(user: UserRow)(implicit userService: UserService)
extends PluggableUserService {
//------------------------------------------------------------------------
override def roles: List[Role] = {
userService.roles(user)
}
}
最后可以在控制器中做:
@Singleton
class Application @Inject() (implicit
val messagesApi: MessagesApi,
session: Session,
deadbolt: DeadboltActions,
userService: UserService) extends Controller with I18nSupport {
import services.PluggableUserService._
def index = deadbolt.WithAuthRequest()() { implicit request =>
Future {
val user: UserRow = userService.findUserInSession(session)
// auto-magically plugs the service to the model
val roles = user.roles
// ...
Ok(views.html.index)
}
}
是否有任何 Scala 方式可以帮助不必在 Pluggable Service 对象中编写样板代码?Pluggable Service 名称有意义吗?