The following is a typical layout of a Play application project:
myProject
+ app
+ controllers
+ models
+ views
I think that the content controllers, modelsand viewsit is clear to most of us. Now suppose we need to implement a DAO service using the cake pattern:
DaoServiceComponent.scala
trait DaoServiceComponent[A] {
def daoService: DaoService
trait DaoService {
def insert(entity: A): Future[A]
def find(id: Id): Future[Option[A]]
...
}
}
trait DefaultDaoServiceComponent[A] extends DaoServiceComponent[A] {
this: DaoComponent[A] =>
def daoService = new DaoService {
def insert(entity: A) = dao.insert(entity)
def find(id: Id) = dao.find(id)
...
}
}
DaoComponent.scala
trait DaoComponent[A] {
def dao: Dao
trait Dao {
def insert(entity: A): Future[A]
def find(id: Id): Future[Option[A]]
...
}
}
UserDaoComponent.scala
trait UserDaoComponent extends DaoComponent[User] {
protected val collection: JSONCollection
def dao = new Dao {
def insert(entity: User): Future[User] = {
...
}
def find(id: Id): Future[Option[User]] = {
...
}
}
}
And finally, we connect everything in our controller object, as usual:
object Users extends Controller {
private val userService: DaoServiceComponent[User]#DaoService =
new DefaultDaoServiceComponent[User]
with UserDaoComponent {
val collection = db.collection[JSONCollection]("users")
}.daoService
def create = Action.async(parse.json) { implicit request =>
request.body.validate[User].fold(
valid = { user =>
userService.insert()..
...
}
}
Now back to our mock draft, where we have to put DaoServiceComponent, DaoComponent, UserDaoComponentand any other support class? Should these files be cataloged services?
myProject
+ app
+ controllers
+ models
+ services
+ DaoComponent.scala
+ DaoException.scala
+ DaoServiceComponent.scala
+ EmailServiceComponent.scala
+ RichEmailComponent.scala
+ ServiceException.scala
+ UserDaoComponent.scala
+ ...
+ views
source
share