Play in practice

16,274 views

Published on

Slides from the SF Scala talk on "Play in Practice", 4/18/2013 Will Sargent

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
16,274
On SlideShare
0
From Embeds
0
Number of Embeds
13,847
Actions
Shares
0
Downloads
48
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Play in practice

  1. 1. PLAY IN PRACTICE/Will Sargent @will_sargent
  2. 2. PREAMBLEThis is going to be a broad talk.
  3. 3. USAGEThis talk does not attempt to be universal to all situations.YMMV.
  4. 4. WHAT IS PLAY?Play is a web application framework.
  5. 5. THESIS STATEMENTPlay is awesome.
  6. 6. WHY PLAY IS AWESOME?Because Play is Simple.
  7. 7. HERES WHAT PLAY DOES:Takes in an HTTP request.Returns (or streams) a response.
  8. 8. HERES WHAT PLAY DOESNT DO:It doesnt tie an HTTP request to a thread.It doesnt tie an HTTP session to memory.It doesnt assume you want convenient but unsafepractices.It doesnt mandate a particular object relationalframework.It doesnt mandate a particular template library.It doesnt mandate a particular routing format.
  9. 9. HERES WHAT PLAY PROVIDES AS OPTIONS:"Always-on" Build SystemHTTP APITemplatesForm HandlingJSON support
  10. 10. BUILD SYSTEMModified SBT, recompiles pages on the fly in developmentmode.Type "play idea" or "play eclipse" to generate the files foryour IDE.
  11. 11. FRONT CONTROLLERRouting API (with LangPathBindable andQueryStringBindable)Action: asynchronous and stateless by default.Immutable HTTP: cookies, request, response, headers, etc.Backed by Akka and Netty.
  12. 12. PRESENTATIONCompiled template language (Twirl, Scaml, Jade).Built-in helpers for rendering forms.Support for Twitter Bootstrap, LESS, jQuery, etc.
  13. 13. JSONFormatting to JSONParsing of JSON objectsJsPath, automatic validation, read and write combinators
  14. 14. SO, WHY DOES THIS MATTER?
  15. 15. THE BUSINESS REQUESTMake a website!
  16. 16. MAKE TWO WEBSITES!ProductAdmin
  17. 17. MAKE MORE WEBSITES!ProductAdminCustomer ServiceBusiness AnalyticsBusiness ContentJobs Queue
  18. 18. THE PROBLEMIn a complex web application, many different front ends needto look at the same data, from different angles.Touching the database directly is dangerous and messy.
  19. 19. THE SOLUTIONIn complex applications, use loosely coupled, stateless,composable services.
  20. 20. HOW?Create a Play HTTP front end, backed by Akka.Create a business domain services, backed by Akka.Use Akka to pass messages between Play and the domainservices.Present information using query services.
  21. 21. ALAN KAY ON OOP“ I thought of objects being like biological cellsand/or individual computers on a network,only able to communicate with messages (somessaging came at the very beginning -- ittook a while to see how to do messaging in aprogramming language efficiently enough tobe useful). ”
  22. 22. COMMAND / QUERY RESPONSIBILITYSEGREGATION (CQRS)Command: a message intending a change of state.Event: a message indicating that state has changed.Fault: a message indicating failure to execute a command.
  23. 23. CQRS MAPPED ONTO PLAYProcessing Commands using POSTQuerying for Data with GETBroadcasting Events with Streaming
  24. 24. PROCESSING COMMANDSValidate all input.where possible.Be very careful when handling passwords and credit cardnumbers.Use value classes
  25. 25. COMMANDSdef sendCommand(command : Command) : Future[Either[Fault,Event]]
  26. 26. CQRS
  27. 27. COMMANDtrait Command extends Productsealed abstract class AuthenticationCommand extends Commandcase class AuthenticateWithPasswordCommand(email:Email,password:String,rememberMe:Boolean)extends AuthenticationCommand {override def toString = "AuthenticateWithPasswordCommand("+ email + "," + rememberMe + ")"}
  28. 28. EVENTcase class UserAuthenticatedEvent(userId: UserID,series: Option[Long] = None,token: Option[Long] = None)extends AuthenticationEvent
  29. 29. FAULTtrait AuthenticationFaultcase class InvalidSessionCookieFault() extends AuthenticationFault
  30. 30. QUERYcase class UserInfo(id: UUID, email: Email, fullName: String)class UserInfoService {def lookup(uuid: UUID)(implicit c:Credentials): Option[UserInfo]def findByName(name: String)(implicit c:Credentials) : TraversableOnce[UserIn}
  31. 31. QUERY PRACTICES:Objects should be immutableReturn ranges or streams over unbounded lists.Dont expose repository logic (i.e. HQL, CQL, etc)Making a good query builder is hard; avoid yak shaving.
  32. 32. CONTEXT AND AUTHENTICATIONUse or to set up aWrappedRequest context.Pass the request context around implicitly in everytemplate.The request context will contain all the state you need (i.e.Credentials).Make helpers take the context as an implicit as needed.Sidenote: helpers are great for keeping logic out oftemplates.play2-rememberme SecureSocial
  33. 33. EXAMPLE TEMPLATE@(u: UserInfo)(implicit ctx: Context)@layout(title = "User Page") {@ctx.me.map { u =><p>This is your user page.</p>}<p>User page of @{u.fullName}.</p>}
  34. 34. STREAMINGYou send an event.Event goes through an Iteratee.Iteratee broadcasts event using Socket and Hub model.Play uses Server Sent Events to stream JSON to clientsJavascript picks up that JSON from SSE, handles display.is the best reference.Sidenote: also check outlilavert.x
  35. 35. EVERYTHING ELSELoggingMetricsTesting
  36. 36. LOGGINGPlays internal logger isnt the greatest.Fortunately, its not hardcoded and you can ignore it.Make your own wrapper over SF4LJ & Logback (orgrizzled, or typesafe logging).
  37. 37. METRICShas a Scala option.Map it through Globals onRequest method.Metrics
  38. 38. TESTINGUnit testing a stateless app is very easy.Swapping out services with mocks/stubs may be easierwith DI (I use Subcut).Functional and integration testing with FakeRequest andFluentlenium almost painless.
  39. 39. LOAD TESTINGUse jconsole and .Dont know how useful Typesafe Console is.Apache JMeter
  40. 40. QUESTIONS?Theres an award!

×