Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
77: Play Controllers and Actions
When you first start with Play, it’s incredibly tempting to treat your controllers like a dumping ground. You have a request coming in, you need to do some work, and you need to send a response back. It feels natural to just write a big method that does everything from validating a session token to calling the database and formatting the JSON. I've seen this happen in countless codebases, and it always leads to the same place: the "Fat Controller."
The temptation of the monolithic handler
Let's say we're building a system to manage a library's book inventory. You might write a controller method to handle updating a book's status like this:
class BookController @Inject()(cc: ControllerComponents, bookRepo: BookRepository) extends AbstractController(cc) {
def updateStatus(bookId: Long) = Action { implicit request =>
// 1. Manual Authentication
val user = request.session.get("user_id")
if (user.isEmpty) {
BadRequest("You must be logged in")
} else {
// 2. Manual Authorization
val isAdmin = bookRepo.checkAdminStatus(user.get)
if (!isAdmin) {
Forbidden("Only admins can change book status")
} else {
// 3. Business Logic
bookRepo.markAsAvailable(bookId)
Ok("Book updated successfully")
}
}
}
}
On the surface, this works. It's explicit. But as soon as you add a deleteBook or addBook method, you'll realize you're copy-pasting those first ten lines of authentication and authorization logic everywhere. You've coupled your HTTP handling (the session) with your business rules (admin status) and your response logic. If the way we handle sessions changes, you're hunting through twenty different methods to update the logic.
Decoupling with Action Composition
The "Play way" to solve this is to stop thinking of the controller method as the starting point and start thinking about Actions as a pipeline. In Play, an Action isn't just the block of code that runs; it's a wrapper that can be composed. I prefer to move the cross-cutting concerns—like "Is this person an admin?"—into a custom ActionBuilder.
By creating a specialized Action, we can extract the user and the permission check before the controller method is even invoked. This lets the controller focus on exactly one thing: coordinating the request to the service layer.
// An ActionBuilder that ensures the user is an Admin
class AdminAction @Inject()(val parser: BodyParsers.Default, bookRepo: BookRepository)
extends ActionBuilder[AdminRequest, AnyContent] {
override def invokeBlock[A](request: Request[A], block: (AdminRequest, A) => Future[Result]) = {
request.session.get("user_id") match {
case Some(userId) if bookRepo.checkAdminStatus(userId) =>
block(new AdminRequest(request, userId), request.body)
case Some(_) =>
Future.successful(Forbidden("Admin access required"))
case None =>
Future.successful(Unauthorized("Please log in")))
}
}
}
case class AdminRequest(request: Request[_], userId: String) extends WrappedRequest[AnyContent]
Now, look at how the controller transforms. We inject our AdminAction and use it instead of the generic Action:
class BookController @Inject()(cc: ControllerComponents, bookRepo: BookRepository, adminAction: AdminAction)
extends AbstractController(cc) {
def updateStatus(bookId: Long) = adminAction { implicit request =>
bookRepo.markAsAvailable(bookId)
Ok("Book updated successfully")
}
}
Trading simplicity for scalability
You might look at this and think, "I just wrote a whole new class and a case class just to save five lines of code in my controller." And for a tiny prototype, you're right—it's overkill. But the trade-off here is about the cognitive load of the developer. When I open BookController now, I don't have to parse the authentication logic to understand what updateStatus actually does. I see adminAction and I know exactly who is allowed in.
Furthermore, this makes testing significantly easier. You can test the AdminAction in isolation to ensure your security logic is bulletproof, and then you can test your controller methods by mocking the action or providing a dummy AdminRequest. You've moved from a world where your security is a series of if/else blocks scattered across your app to a world where security is a declarative part of your route handling.
📋 Practical Task
Build a Permission-Based Action for a "Premium" Content Gate
You are building a digital magazine. Some articles are free, but others are restricted to "Premium" subscribers. Currently, the check is being done manually inside every single controller method.
Your Task:
Create a custom PremiumAction (extending ActionBuilder) that:
- Checks the request session for a
"subscription_level"key. - If the value is
"premium", it allows the request to proceed to the controller block. - If the value is
"basic"or missing, it returns aPaymentRequired(402) result with the body"Please upgrade your account to view this content."
Once the Action is built, implement a MagazineController with a method readPremiumArticle(id: String) that uses this PremiumAction to protect the content. The method itself should simply return an Ok result with the text "Welcome to the inner circle!".
There are no comments for now.