Play in practice

Uploaded on

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

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

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. PLAY IN PRACTICE/Will Sargent @will_sargent
  • 2. PREAMBLEThis is going to be a broad talk.
  • 3. USAGEThis talk does not attempt to be universal to all situations.YMMV.
  • 4. WHAT IS PLAY?Play is a web application framework.
  • 5. THESIS STATEMENTPlay is awesome.
  • 6. WHY PLAY IS AWESOME?Because Play is Simple.
  • 7. HERES WHAT PLAY DOES:Takes in an HTTP request.Returns (or streams) a response.
  • 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. HERES WHAT PLAY PROVIDES AS OPTIONS:"Always-on" Build SystemHTTP APITemplatesForm HandlingJSON support
  • 10. BUILD SYSTEMModified SBT, recompiles pages on the fly in developmentmode.Type "play idea" or "play eclipse" to generate the files foryour IDE.
  • 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. PRESENTATIONCompiled template language (Twirl, Scaml, Jade).Built-in helpers for rendering forms.Support for Twitter Bootstrap, LESS, jQuery, etc.
  • 13. JSONFormatting to JSONParsing of JSON objectsJsPath, automatic validation, read and write combinators
  • 15. THE BUSINESS REQUESTMake a website!
  • 16. MAKE TWO WEBSITES!ProductAdmin
  • 17. MAKE MORE WEBSITES!ProductAdminCustomer ServiceBusiness AnalyticsBusiness ContentJobs Queue
  • 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. THE SOLUTIONIn complex applications, use loosely coupled, stateless,composable services.
  • 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. 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. 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. CQRS MAPPED ONTO PLAYProcessing Commands using POSTQuerying for Data with GETBroadcasting Events with Streaming
  • 24. PROCESSING COMMANDSValidate all input.where possible.Be very careful when handling passwords and credit cardnumbers.Use value classes
  • 25. COMMANDSdef sendCommand(command : Command) : Future[Either[Fault,Event]]
  • 26. CQRS
  • 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. EVENTcase class UserAuthenticatedEvent(userId: UserID,series: Option[Long] = None,token: Option[Long] = None)extends AuthenticationEvent
  • 29. FAULTtrait AuthenticationFaultcase class InvalidSessionCookieFault() extends AuthenticationFault
  • 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. 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. 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. EXAMPLE TEMPLATE@(u: UserInfo)(implicit ctx: Context)@layout(title = "User Page") { { u =><p>This is your user page.</p>}<p>User page of @{u.fullName}.</p>}
  • 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 the best reference.Sidenote: also check outlilavert.x
  • 35. EVERYTHING ELSELoggingMetricsTesting
  • 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. METRICShas a Scala option.Map it through Globals onRequest method.Metrics
  • 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. LOAD TESTINGUse jconsole and .Dont know how useful Typesafe Console is.Apache JMeter
  • 40. QUESTIONS?Theres an award!