Interaction & Presentation: MVC, MVP, MVVM and Data Flow
"The essential purpose of MVC is to bridge the gap between the human user's mental model and the digital model that exists in the computer." — Trygve Reenskaug, MVC: Xerox PARC 1978-79 (his own page on the pattern)
Summary: MVC, MVP, MVVM, Presentation Model and Flux are all answers to one question: where does the code that talks to the user live, and how does it stay separate from the rules of the business? Everything else (controllers, view models, resources, templates) is a detail of that split. Focus: Separated Presentation, the original Smalltalk MVC versus web MVC, MVP (Passive View and Supervising Controller), MVVM and data binding, Model 2 and the front controller, unidirectional data flow (Flux, Redux, Elm) and server-driven UIs (Livewire, HTMX), API-first presentation (resources, DTOs, view models, HATEOAS), input and output handling, thin controllers, templating and escaping, UI state and sessions, Clean/Hexagonal placement, BFF and micro-frontends, and how to test all of it, in Go and Laravel. Learning goal: Build one "orders list plus create order" screen as a Blade page, a JSON API and an Inertia page in Laravel, and as a template page plus JSON in Go, with every business rule living in one use case that none of those presentations contains.
This page is the complete reference for the presentation side of design: how input comes in, how output goes out, and how both stay thin. It does not re-teach its neighbours. Dependencies and layering rules are on Dependency Inversion; one-reason-to-change is on Single Responsibility; event loops and callbacks are on Control Flow & Event Handling; repositories and mapping are on Data Persistence in Design; the network cost of splitting a UI from its backend is on Distribution of Components; error mapping is on Error & Exception Handling; and the threats around input and output are on Security by Design. Architecture-level pieces (gateway, BFF, layered styles) are on API Gateway, BFF & Service Mesh and Layered Monolithic Architecture.
Page map
| If you are looking for | Go to |
|---|---|
| The whole topic in a few tables | Everything in one minute |
| Why presentation must be separate | Why it exists |
| Reenskaug 1979, Smalltalk, Fowler's GUI Architectures, Model 2 | Where it comes from |
| MVC, MVP, MVVM, Presentation Model, Model 2, front controller | The concepts, one by one |
| Unidirectional flow, Livewire, HTMX, Inertia | Data flow and server-driven UIs |
| JSON resources, DTOs, view models, HATEOAS | API-first presentation |
| Form requests, validation, commands, presenters, serializers | Input and output |
| Fat vs thin controllers, actions, use cases | Thin controllers |
| Escaping, XSS, sessions, UI state | Mechanics |
| The same screen in Go and in Laravel | Go, Laravel |
| Classic problems (fat controller, leaking models, N+1 in views, double submit) | Solving the classic problems |
| Which pattern for which UI | Choosing |
| Clean/Hexagonal placement, BFF, micro-frontends, scaling | In architecture |
| A hands-on build with tests | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts section.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Separated Presentation | Domain code never knows how it is shown | Order has no HTML in it | Every new screen copies rules |
| Model | The domain data and rules (or the data a screen needs) | Order, CreateOrder | Rules end up in templates |
| View | Turns data into pixels, HTML or JSON | Blade file, Go template | Formatting scattered in controllers |
| Controller | Turns user input into calls on the model | POST /orders handler | Handlers grow into 300-line scripts |
| Presenter (MVP) | Drives a passive view; holds all UI decisions | presenter.OnSubmit | UI logic cannot be unit-tested |
| ViewModel (MVVM) | UI state and commands the view binds to | OrdersViewModel | Code-behind full of widget calls |
| Presentation Model | The same idea as ViewModel, older name | Fowler 2004 | Widget APIs hold the state |
| Front controller | One entry point for every request | Laravel's router kernel, Go's ServeMux | Auth and logging copied per page |
| Unidirectional data flow | State changes only through actions | Redux, Elm, Flux | Cascading updates nobody can predict |
| Server-driven UI | Server renders HTML, browser swaps it in | Livewire, HTMX | Duplicate state client and server |
| DTO / Resource | Wire representation of a model | OrderResource | Column rename breaks the mobile app |
| View model (web) | Display-ready data for one screen | OrderRow with Total: "12.50" | Templates full of formatting logic |
| Form Request | Validation and authorisation at the boundary | StoreOrderRequest | Invalid data reaches the domain |
| Presenter (Clean Arch) | Implements the use case's output port | JSON or HTML presenter | Use case imports a template engine |
| BFF | One backend per user experience | mobile-bff, web-bff | One API fits no client |
The patterns in one table.
| Pattern | Who handles input | Who updates the screen | Where UI state lives | Typical home |
|---|---|---|---|---|
| Forms and Controls | Widget event handlers | The handler, by hand | In the widgets | VB, Delphi, small admin tools |
| MVC (Smalltalk) | Controller | View observes Model | Model | Smalltalk-80 |
| MVC (web, Model 2) | Controller action | Template render per request | Session, database | Laravel, Rails, Spring MVC, Go handlers |
| MVP (Passive View) | Presenter | Presenter calls view setters | Presenter | Android classic, WinForms |
| MVP (Supervising Controller) | Presenter | Binding for simple parts, presenter for complex | Model plus presenter | WinForms with binding |
| MVVM / Presentation Model | View binds to ViewModel | Binding engine | ViewModel | WPF, .NET MAUI, Vue, Knockout |
| Flux / Redux / Elm | Dispatch of actions | View re-renders from state | One store | React apps, Elm |
| Server-driven (HTMX, Livewire) | HTTP event to server | Server returns HTML fragment | Server (session, component) | Laravel Livewire, HTMX |
Where each piece lives in your tools.
| Layer | Go | Laravel 13 |
|---|---|---|
| Entry point | http.ServeMux, middleware chain | routes/web.php, routes/api.php, middleware |
| Input validation | Decode and check in the handler or a Decode helper | FormRequest with rules() |
| Controller | func(w, r) handler | Controller class, single-action __invoke |
| Use case | A Service method | An action class such as CreateOrder |
| View model | A struct built by the handler | A readonly class or View::composer data |
| HTML view | html/template | Blade |
| JSON representation | DTO struct with json tags | JsonResource, ResourceCollection |
| SPA bridge | Plain JSON API | Inertia, Livewire |
| Tests | net/http/httptest | $this->get(), postJson(), assertInertia() |
Why it exists
A user interface changes for different reasons and at a different speed than the business rules. Marketing wants a new layout every month; the rule "an order total must be positive" has not changed in ten years. When both live in one file, a layout change risks the rule, and a second UI (a mobile app, a CLI, an admin tool, a test) must copy the rule. Fowler names the cure Separated Presentation: put the domain in objects that are "completely self contained and work without reference to the presentation", and let any number of presentations sit on top.
| Mixed presentation and domain | Separated presentation |
|---|---|
| One file is quick to write | More files and names to learn |
| The rule is tested through a browser or HTTP | The rule is tested as a plain function |
| A second UI copies the rule | A second UI is a new adapter |
| Layout change can break pricing | Layout change touches templates only |
| Designer and backend developer edit the same file | Each edits their own layer |
| Easy to see "everything about this page" | Must follow one hop between layers |
| Risk: fat controller, logic in templates | Risk: needless layers for a three-field form |
The picture shows the three classic shapes. In MVC the View reads the Model and the Controller turns input into Model calls. In MVP the View is a thin interface and the Presenter does the talking in both directions. In MVVM the View binds to a ViewModel and a binding engine keeps them in sync. In every case the Model has no arrow pointing back at the UI.
The analogy we reuse on this page: a restaurant with a kitchen and a dining room. The kitchen (domain) cooks to a recipe no matter who ordered. The waiter (controller) takes the order, brings it to the kitchen in the kitchen's words ("two risottos"), and brings the plate back. The plating and the menu design (view) change with the season. A takeaway window, a delivery app and a table service all use the same kitchen. If the chef has to know whether the customer sits inside or outside, the kitchen has become a dining room.
Three common misunderstandings, up front
- "MVC is a folder layout."
app/Http/Controllers,app/Modelsandresources/viewsis a layout. MVC is a rule about dependencies: the model must not know the view. - "The controller is where the logic goes." In the web version the controller is a request handler. It parses, calls, and picks a response. The logic belongs in a use case or the domain.
- "MVC, MVP and MVVM are three different architectures." They are three answers to the same question (who updates the screen, and where does UI state live). The differences are small; the separation from the domain is the part that matters.
Where it comes from
Smalltalk and Reenskaug, 1978-1979. Trygve Reenskaug was a visiting scientist with the Learning Research Group at Xerox PARC from 1978 to 1979. On his own page he says he wrote "the original MVC note at Xerox PARC in 1978", that it defined four terms (Model, View, Controller and Editor), and that the first set of names was Model-View-Editor. A one-page December 1979 note gives the definitions we still use:
"Models represent knowledge." — Trygve Reenskaug, Models - Views - Controllers, 10 December 1979
"A view is a (visual) representation of its model. It would ordinarily highlight certain attributes of the model and suppress others. It is thus acting as a presentation filter." — Trygve Reenskaug, Models - Views - Controllers, 10 December 1979
The same note keeps input out of the view: "a view should never know about user input, such as mouse operations and keystrokes." The controller is "the link between a user and the system". Reenskaug adds that Jim Althoff implemented a version for Smalltalk-80 after he had left PARC and used the word Controller "somewhat differently" from him. This is the first source of confusion: even the original had two meanings.
Forms and Controls, then Fowler's survey (2006). Martin Fowler's GUI Architectures describes the Forms and Controls style (widgets with handlers, common in 1990s visual tools) and then what MVC really contributed:
"The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen." — Martin Fowler, GUI Architectures, martinfowler.com, 18 July 2006
He says MVC is best thought of as "a set of principles including the separation of presentation from domain logic and synchronizing presentation state through events (the observer pattern)", and calls it "one of the most misunderstood architectural patterns around". Two things clearly worked and survived in every variant: Separated Presentation and Observer Synchronization. The view/controller split is the part that mostly disappeared.
MVP, Presentation Model, Supervising Controller, Passive View (1990s-2006). Fowler traces MVP to Taligent in the 1990s (the Potel paper) and to the Dolphin Smalltalk developers. In MVP the widgets are a view with no behaviour, and "the active reaction to user acts lives in a separate presenter object". In July 2004 he wrote Presentation Model and noted that it is "increasingly known as MVVM". In 2006 he split MVP into two named variants: Supervising Controller and Passive View. Those pages are marked as draft by Fowler himself; we cite them as definitions of the terms, not as final truth.
MVVM (2005, Microsoft). MVVM comes from the WPF world and is described by Microsoft's .NET MAUI documentation: views bind to view model properties, and "the binding of views to a property in a data source should be the view's principal dependency on its corresponding view model." We did not read John Gossman's original 2005 blog post; the date and origin come from secondary summaries and are marked as such.
The web: Model 2 and the front controller. In the late 1990s Java servlet/JSP guidance described "Model 1" (JSP page does everything) and "Model 2" (a servlet controller picks a model operation and forwards to a JSP view). We did not read the original Sun documents; Model 2 here is described from secondary sources and from how Struts, Spring MVC, Rails, Laravel and Django all work today. Fowler's Patterns of Enterprise Application Architecture names the pieces: Page Controller (one controller per page or action) and Front Controller ("a controller that handles all requests for a Web site", consolidating "security, internationalization, and providing particular views for certain users").
Unidirectional flow (mid 2010s; exact dates are not on the pages we read). Facebook's Flux, Redux (which the Elm guide says was "inspired by The Elm Architecture") and Elm itself replaced two-way bindings with one direction: action, store or reducer, view. Flux's documentation says it "eschews MVC in favor of a unidirectional data flow" and explains why: with MVC, "marking a single thread as read would update the thread model, and then also need to update the unread count model". The Flux project is archived; the idea lives on in Redux and in every reducer-style state library.
Hypermedia revival (2020s). HTMX's essay "Hypermedia-Driven Applications" (Carson Gross, 2022) argues for a third way between multi-page apps and SPAs. Livewire (Laravel) and Inertia (Laravel, Rails and others) each take a different position on how much of the view layer stays on the server. We cover all three below.
| Year | Event | Why it matters |
|---|---|---|
| 1978-79 | Reenskaug writes MVC notes at Xerox PARC | Model, View, Controller, Editor named |
| 1980s | Smalltalk-80 ships its MVC class library | The controller becomes the input handler of a widget |
| 1990s | Forms and Controls (VB, Delphi), MVP at Taligent | Rapid UIs, and the testing problem |
| late 1990s | Servlet/JSP Model 2, Front Controller | Web MVC is born |
| 2004 | Fowler: Presentation Model | UI state in its own class |
| 2005 | MVVM at Microsoft (WPF), secondary source | Binding replaces the presenter's wiring |
| 2006 | Fowler: GUI Architectures, Passive View, Supervising Controller | A vocabulary for MVP |
| mid 2010s | Flux, Redux, Elm Architecture (dates not on the pages we read) | One-way data flow |
| 2022 | HTMX essay "Hypermedia-Driven Applications" (Livewire and Inertia came in the same period) | Server-driven UIs return |
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a request or event timeline, real scenarios, how the two languages express it, and the fix.
Separated Presentation Must-know
In plain words: the part of the program that knows what an order is must not know that it is displayed in a table.
Common misunderstanding: "If I use a template engine, my presentation is separated." A template engine separates HTML from PHP. Separated Presentation is about domain from UI: a template that calls Order::where(...) or contains the discount rule is not separated.
Definition: domain objects work without reference to presentation and can support several presentations at once; presentation objects depend on the domain, never the reverse.
Actor Action Knows about
1 Domain Order.Create validates total > 0 nothing about HTTP or HTML
2 Controller parses "12.50" to 1250 cents HTTP, forms; calls the domain
3 View renders "12.50" display format; receives text
4 Another UI CLI command calls the same Create stays free of HTMLReal scenarios: a web page and a mobile API that must enforce the same rules; an Artisan command that imports orders from CSV through the same use case; a queued job; a test that checks a rule without a browser.
| Where the rule lives | Second UI costs | Test cost |
|---|---|---|
| In the controller | Copy-paste or call a controller | HTTP request needed |
In the model (Eloquent saving hook) | Works for every caller of the model | Database needed |
| In a use case or action | New adapter only | Plain function call |
Fix / how to use it. The Go version is the order package in the lab: it has no net/http, no html/template. The Laravel version is the CreateOrder action. Both are shown in Go and Laravel.
MVC as originally meant Must-know
In plain words: the user clicks a button on a screen; a controller catches the click and tells the model; the model changes and announces it; every view that shows that model redraws itself.
Common misunderstanding: "Laravel's OrdersController is the C of Reenskaug's MVC." Reenskaug's controller catches mouse and keyboard events inside a running desktop program. The web controller handles one HTTP request and ends. They share a name, not a job.
Definition: a Model holds the knowledge, a View presents it and asks the model questions, a Controller links user input to model messages. Views register as observers of the model; the model never mentions a view.
User Controller Model View
1 clicks "Pay"
2 onClick -> model.pay()
3 status = paid
4 notify observers
5 view.update() reads model
6 redraws status labelReal scenarios: a spreadsheet where editing a cell updates a chart and a status bar at once (Fowler's own example for why observers matter); a desktop IDE with two panes showing the same file; a live dashboard where several widgets observe one metrics model.
| Concern | Original MVC | Web MVC |
|---|---|---|
| Who observes the model | Views, via the observer pattern | Nobody; the next request re-reads |
| Life of the controller | The whole session | One request |
| UI state | Model or view | Session, cookie, query string, DB |
| Model changes the view without input | Yes | Only with polling, SSE or WebSocket (see real-time) |
Fix / how to use it. When you build a real-time screen on the web, you are rebuilding original MVC over a network: the "notify observers" arrow becomes a message on a channel. See Flux and server-driven UIs.
Web MVC, Model 2 and the front controller Must-know
In plain words: every request enters through one door (the front controller), a router picks a controller action, the action calls the model, and then a view turns the result into the response.
Common misunderstanding: "The model is the Eloquent class (or the database table)." In the web version the model is the domain: rules and data. An Eloquent model is an Active Record, which mixes data access and domain state; it can act as a model, but it is not what the term means.
Definition: Front Controller is one handler for all requests that runs the shared behaviour (security, locale, logging) then dispatches. Page Controller is one controller object per page or action. Model 2 is the web arrangement: controller selects behaviour, model does the work, view renders.
Browser Server
1 POST /orders -> router matches POST /orders
2 middleware: session, CSRF token check, auth
3 StoreOrderRequest validates, authorises
4 controller calls CreateOrder(customer, cents)
5 use case saves, dispatches OrderPlaced
6 controller returns redirect to /orders
7 <- 303 Location (Post/Redirect/Get)
8 GET /orders -> controller reads orders, builds rows
9 Blade renders the HTML
10 <- 200 HTMLReal scenarios: every Rails, Django, Spring MVC, Laravel and ASP.NET MVC application; a Go service using http.ServeMux with method patterns such as "GET /orders"; an admin panel.
| Framework | Front controller | Routing | Controller | View |
|---|---|---|---|---|
| Laravel 13 | public/index.php and the HTTP kernel | routes/web.php, routes/api.php | Class in app/Http/Controllers | Blade |
| Go net/http | http.Server with a ServeMux | Patterns like GET /orders | func(w http.ResponseWriter, r *http.Request) | html/template |
| Spring MVC | DispatcherServlet | @RequestMapping | @Controller | Thymeleaf, JSP |
| Rails | Rack plus the router | config/routes.rb | ApplicationController subclass | ERB |
| Django | URL dispatcher | urls.py | View function (their "view" is a controller) | Template |
| ASP.NET Core MVC | Middleware pipeline | Attribute or conventional routes | Controller class | Razor |
Fix / how to use it. Keep the middleware for cross-cutting concerns (authentication, CSRF, rate limits, request IDs), the Form Request or decode step for input, the controller for translation, and everything else out of the HTTP layer. See Input and output.
MVP: Passive View and Supervising Controller Important
In plain words: the screen is a dumb set of widgets that expose "show this" and "tell me what the user typed"; a presenter object decides everything and is the only thing tests need to touch.
Common misunderstanding: "MVP is just MVC with a renamed controller." The difference is who knows whom. In MVC the view reads the model. In MVP the view knows only the presenter; Fowler's Passive View has "no dependencies in either direction between the view and the model."
Definition: Passive View: "the view is made completely passive and is no longer responsible for updating itself from the model"; the presenter sets every widget. Supervising Controller: the view maps simple fields by declarative binding, and the controller "intervenes only when effects are needed that are beyond what can be achieved declaratively."
User View (interface) Presenter Model/use case
1 types "12.50", clicks Create
2 view.onSubmit() ---------> OnSubmit("Ada", "12.50")
3 parses, calls use case ---> Create(...)
4 <--- ValidationError{customer: required}
5 <--- ShowFieldError("customer", "required")
6 renders the errorReal scenarios: classic Android activities with a Presenter; WinForms forms where the form implements IOrdersView; a terminal UI where the same presenter drives a TUI view and a test fake; any screen whose behaviour you need to test without a GUI toolkit.
| Variant | Who maps model to widget | Testability | Cost |
|---|---|---|---|
| Passive View | Presenter, field by field | Highest: fake view | More presenter code and view interface methods |
| Supervising Controller | Binding for simple fields; presenter for complex cases | High, but binding is untested | Two mechanisms to learn |
| Forms and Controls (for contrast) | Event handlers in the form | Low: widgets in every test | Least code at the start |
Fix / how to use it. The Go mvp package in the lab is a Passive View. The presenter holds the logic, fakeView records calls, and the test never opens a window. In web applications this pattern is rare because the server already is the presenter; it comes back when a Go TUI, a mobile app or a desktop client needs the same behaviour.
MVVM and data binding Important
In plain words: the screen shows whatever the view model says; when the view model's state changes the screen updates itself, and when the user types the view model's state updates, with no handwritten glue.
Common misunderstanding: "A ViewModel is the model with a different name" or "the ViewModel is a DTO." A view model is behaviour plus state for a screen (including commands like "Create is enabled only when the form is valid"). A DTO is a data shape. (On the web the term view model is also used for a plain data holder for a template; see View models.)
Definition: the View declares bindings; the ViewModel exposes properties and commands and raises change notifications; the Model is the domain. Microsoft's guidance: "don't reference view types, such as Button and ListView, from view models," so the view model can be tested in isolation. In .NET the notification contract is INotifyPropertyChanged; commands are ICommand with Execute and CanExecute; collections use ObservableCollection<T>; the view is wired to the view model through the BindingContext property.
User View (XAML/Vue) ViewModel Model
1 types in field
2 two-way binding ----> Total = "12.50"
3 CreateCommand.CanExecute() true
4 clicks Create command binding ----> CreateCommand.Execute()
5 IsBusy = true -> PropertyChanged
6 spinner appears (binding reacts)
7 orders.Create(...) -----> rules
8 IsBusy = false; Rows updated -> PropertyChanged
9 table re-rendersReal scenarios: WPF and .NET MAUI apps; Vue components (ref, computed and v-model play the same roles); Knockout and Angular templates; SwiftUI's ObservableObject. In PHP and Go, MVVM appears in the browser (Vue or Alpine on top of your JSON API), not on the server.
| Concept | .NET (MAUI, WPF) | Vue | Livewire |
|---|---|---|---|
| View model | Class implementing INotifyPropertyChanged | Component state (ref, reactive) | Livewire component class |
| Change notification | PropertyChanged event | Reactivity system | Request/response diff |
| Command | ICommand | Method handler | Public method called from wire:click |
| Two-way binding | {Binding Mode=TwoWay} | v-model | wire:model |
| Where it runs | Client | Client | Server |
Fix / how to use it. On the server side, use the idea (a per-screen object with display-ready state) without the binding engine: see View models. On the client side, keep the view model free of DOM calls so it can be tested with plain functions.
Presentation Model Good to know
In plain words: pull the screen's state and behaviour out of the widgets into one plain class; the widgets just display it.
Common misunderstanding: "It is only a facade over one domain object." Fowler: "Presentation Model may interact with several domain objects, but Presentation Model is not a GUI friendly facade to a specific domain object." It models the screen, which may combine many domain objects.
Definition: a self-contained class that represents all the data and behaviour of the UI window without any of the controls; "a view then simply projects the state of the presentation model onto the glass." It is the pattern that MVVM later standardised, and VisualWorks Smalltalk called it the Application Model.
View Presentation Model Domain
1 user selects row 3
2 -------------> selectedOrder = row 3
3 canPay = selectedOrder.status == new
4 <-- sync ---- (view enables the Pay button)
5 clicks Pay --> pay() -----------------------------> order.Pay()Real scenarios: an order screen where "Pay is enabled" depends on selection and status; a wizard with step state; a form with dependent drop-downs.
| Pattern | Who owns UI state | Sync mechanism |
|---|---|---|
| Presentation Model | Presentation model | Manual sync or observer |
| MVVM | View model | Declarative data binding |
| Passive View | Presenter | Presenter writes widgets |
Fix / how to use it. Web-side, the OrdersPage struct in the Go snippet and the OrderRowViewModel in Laravel are one-shot presentation models: built per request, rendered, discarded.
View models in web applications Must-know
In plain words: before rendering, build a small object that contains exactly what the page shows, already formatted, so the template only loops and prints.
Common misunderstanding: "Passing the Eloquent model (or the domain struct) to the view is simpler and equivalent." It is simpler for ten minutes. The template then depends on the database columns, triggers lazy-loading queries (see N+1 in views), and formats money in five different places.
Definition: a view model (web sense) is a data structure shaped for one view: display strings, booleans like CanPay, and form state with errors. In Laravel it can be a readonly class, an array, or data attached with a view composer (a callback that runs whenever a view renders, registered with View::composer, used for shared data such as a navigation menu).
Controller View model Template
1 orders = ListOrders()
2 rows = orders.map(OrderRow.from) total = "12.50"
3 status = "NEW"
4 render("orders", rows)
5 for each row: print row.totalReal scenarios: money and date formatting in one place; feature flags and CanPay booleans; shared layout data (current user, unread count) through a composer; a read model for a dashboard that joins four tables.
| Technique | Laravel | Go |
|---|---|---|
| Per-screen data class | OrderRowViewModel (readonly) | OrdersPage, OrderRow structs |
| Shared data for many views | View::composer('layout', ...) or View::share | A function that returns common fields, embedded in each page struct |
| Display helpers | Blade components, accessors, Enum label() | template.FuncMap (keep tiny) |
Fix / how to use it. Put formatting in the view model and unit-test it; keep the template free of arithmetic and queries. Full code is in the lab.
Unidirectional data flow Important
In plain words: nothing changes the screen's data except an action that goes through one function; the screen is always a pure picture of the current data.
Common misunderstanding: "Redux (or Flux) is MVC for the front end." Flux's own documents say it "eschews MVC in favor of a unidirectional data flow", and they describe why two-way bindings led to "cascading updates, where changing one object led to another object changing". It deliberately removes the arrows that MVC views and models share.
Definition: the view dispatches an action ("an object describing what happened", in Redux's words), a reducer (a pure function from previous state and action to next state) computes the new state, and the view re-renders from it. Redux's three principles: a single source of truth, state is read-only, and changes are made with pure functions. The Elm Architecture has the same three parts: Model, View, Update.
View Store/Reducer State
1 click Load ---> dispatch(LoadRequested)
2 Reduce(state, LoadRequested) Loading = true
3 render: spinner
4 (fetch completes) dispatch(OrdersLoaded{...})
5 Reduce(state, OrdersLoaded) Orders = [...], Loading = false
6 render: tableReal scenarios: a React dashboard with Redux Toolkit; an Elm application; a complex form wizard where "undo" and "time-travel debugging" matter; a bug report that includes the list of actions so a developer can replay it.
| Aspect | Two-way binding (MVVM) | Unidirectional flow |
|---|---|---|
| Change path | Any property may be written from anywhere | Only via dispatched actions |
| Predictability | Cascades possible | Order of actions fully determines state |
| Debugging | Inspect live objects | Log or replay actions |
| Boilerplate | Low | Higher (actions, reducers) |
| Fits | Forms, small screens | Large interactive apps with shared state |
Fix / how to use it. The Go flux package in the lab is a 60-line store with a pure Reduce; its test replays an action list twice and compares. On the Laravel side, the same shape appears in Inertia and Livewire (below), where "the server owns the state."
Server-driven UIs: Livewire, HTMX and Inertia Important
In plain words: instead of shipping a big JavaScript app that talks JSON, the server sends HTML (or page data) and the browser swaps it in.
Common misunderstanding: "These tools are just old-fashioned server rendering." They keep the server as the owner of state and rules, but they update parts of the page without a reload. The programming model differs a lot among them.
Definition: HTMX (an HDA, hypermedia-driven application) extends HTML with attributes so that an element can issue a request and swap the returned HTML fragment in place; the server speaks HTML, not JSON. Livewire (Laravel) is a full-stack component framework: a PHP class and a Blade view make a component, and public properties and methods are bound from the browser (wire:model, wire:click) and re-rendered on the server. Inertia "replaces your application's view layer": controllers stay the same, but instead of a Blade template the response is a JavaScript page component name plus props, rendered by Vue, React or Svelte; Inertia intercepts link clicks and fetches JSON for subsequent visits.
Browser Laravel Response
1 GET /app/orders -> controller: Inertia::render('Orders/Index', props)
2 full HTML + page data
3 click "next page" (Inertia Link)
4 XHR with Inertia header -> same controller JSON {component, props}
5 swaps page component, updates history without a reload
1 click "Pay" (hx-post="/orders/7/pay")
2 -> controller pays, renders partial HTML fragment
3 HTMX swaps fragment into #order-7Real scenarios: an internal admin with search-as-you-type (Livewire or HTMX); a SaaS dashboard written in Vue where the team keeps Laravel routing and auth (Inertia); a progressively enhanced list that works without JavaScript (HTMX, with real links and forms underneath).
| Tool | State lives | Server output | View language | Needs a JS framework |
|---|---|---|---|---|
| Blade (plain) | Server, per request | HTML page | Blade | No |
| HTMX | Server | HTML fragments | Any template engine | No |
| Livewire | Server (component state, round-tripped) | HTML diffs | Blade | No (Alpine.js for small client-side behaviour) |
| Inertia | Client page, props from server | JSON props, page component name | Vue, React, Svelte | Yes |
| SPA plus JSON API | Client | JSON | Any | Yes |
Fix / how to use it. Pick by who owns the interaction logic. If the team is server-side-first, start with Blade plus HTMX or Livewire. If a client-side framework is required, Inertia saves you from building and versioning a separate API for that one client; a public API still needs resources. See the Laravel snippet in Laravel.
Command and query separation at the boundary Important
In plain words: a request is either a question ("list orders") or an instruction ("create this order"); treat them differently.
Common misunderstanding: "Controllers should call repositories directly for reads, and services only for writes" (or the opposite). Either extreme works in small apps; the problem is mixing it up per endpoint with no rule, so the next reader cannot predict where a rule lives.
Definition: the controller turns a request into a command (an object with intent and validated data, for example CreateInput{Customer, TotalCents}) and calls a use case; for reads it builds a query (filters, page, sort) and calls a query service that returns a read-shaped result. This is the entry to CQRS if you later split the models; you do not need to split them to benefit from the vocabulary.
Request Controller Application
1 POST /orders {...} -> map to CreateInput -> CreateOrder(cmd) -> returns id or error
2 GET /orders?page=2 -> map to ListQuery -> ListOrders(query) -> returns rowsReal scenarios: an order screen with expensive filters (query side may use a read replica or a search index); an audit requirement where every write has a named command.
| Side | Controller task | Return value | Typical status |
|---|---|---|---|
| Command | Validate, map, call, redirect or return 201 | Identifier or nothing | 201, 303, 422 |
| Query | Parse filters and paging, call, render | Data for the view | 200, 404 |
Fix / how to use it. In Go, the order.CreateInput struct is the command. In Laravel, an action class takes primitives or a small DTO; avoid passing the Request object into the domain.
Data flow and server-driven UIs
The concept blocks above (unidirectional flow and server-driven UIs) are the two modern answers to "who owns state". This section puts them side by side with a decision rule.
| Question | If yes | Then |
|---|---|---|
| Is most state a function of the database and the user's session? | Yes | Server owns state: Blade, HTMX, Livewire |
| Is there complex client-only state (drag and drop, offline, optimistic updates)? | Yes | Client store: Redux Toolkit, Pinia, Elm-style |
| Do you need one backend for a web client, a mobile app and partners? | Yes | API-first with resources and versioning |
| Is your team mostly backend developers who must ship fast? | Yes | Server-driven first; add JS islands where needed |
| Do you need SEO and fast first paint without a build pipeline? | Yes | Server-rendered HTML |
API-first presentation
"API-first" means the JSON (or Protobuf) representation is the primary presentation, designed before any page, and the web UI is one of its clients.
Resources and DTOs Must-know
In plain words: never send your internal object over the wire; send a deliberately designed copy.
Common misunderstanding: "return $order (or json.Marshal(order)) is fine; it is the same data." It couples the wire format to the schema: a renamed column breaks clients, a new password_hash column leaks, and Eloquent relationships or lazy-loaded attributes fire queries during serialisation.
Definition: a DTO (data transfer object) is a plain structure for crossing a boundary. In Laravel the DTO role is played by an API Resource (JsonResource for one model, ResourceCollection or Resource::collection() for many, with automatic links and meta for paginators and whenLoaded for relations). In Go it is a struct with json tags.
Domain order Resource / DTO
1 ID, Customer, TotalCents, id, customer, total_cents, status, created_at
2 Status (enum), CreatedAt, (no internal flags, no password hash)
3 InternalNotes, CostCents (fields chosen deliberately)Real scenarios: a public API that outlives three front ends; an internal field that must never leave the service; a response that must be stable across a database migration.
| Practice | Why | Laravel | Go |
|---|---|---|---|
| Explicit field list | No accidental exposure | toArray() of the resource | DTO struct, not the domain type |
| Stable names | Contract with clients | Resource keys, not column names | json:"total_cents" tags |
Envelope (data, meta, links) | Room for paging and errors | Wrapped by default under data | A {"data": ...} map or struct |
Empty list is [] | Clients crash on null | Collections serialise as [] | Initialise slice with make, not nil |
| Time in UTC ISO 8601 | Unambiguous | toIso8601String() | time.Time encodes RFC 3339 |
| Money in minor units | No float errors | total_cents integer | int64 cents |
Fix / how to use it. Both lab implementations return a data envelope, an ISO timestamp and cents. A contract test (see Testing) pins the exact JSON so a refactor cannot change it by accident.
Versioned responses and HATEOAS Important
In plain words: when the response shape must change, add a new version next to the old one; and optionally let the response tell clients which links they can follow.
Common misunderstanding: "REST requires HATEOAS links in every response, or it is not REST." Fielding's dissertation lists "hypermedia as the engine of application state" as one of four interface constraints. In practice most JSON APIs stop at Richardson level 2 (resources and HTTP verbs); level 3 adds hypermedia controls. Adopt it only if your clients really follow links.
Definition: versioned responses are a deliberate fork of the contract (/api/v1/orders, a Accept: application/vnd.example.v2+json header, or a date-based version). HATEOAS means each representation carries the links or forms for what can be done next (a pay link only when the order is payable). See REST API Design and API Versioning & Evolution for the full treatment.
Client Server
1 GET /api/v1/orders/7 -> 200 {"id":7,"status":"new","links":{"pay":"/api/v1/orders/7/pay"}}
2 follows links.pay -> 200 {"status":"paid","links":{}}
3 old mobile build still calls /api/v1/orders -> unchanged shape
4 new web client calls /api/v2/orders -> new shapeReal scenarios: a mobile app that cannot be force-updated; a partner integration with a contract; a UI that hides the Pay button when the server omits the pay link.
| Strategy | Pros | Cons |
|---|---|---|
URL version (/v1/) | Visible, cache- and log-friendly | Duplicates routes |
| Header version | Clean URLs | Hidden, harder to test by hand |
| Additive changes only | No version needed | Cannot remove or rename |
| HATEOAS links | Server controls available actions | More payload; clients must be written to follow links |
Fix / how to use it. Start with additive changes and a v1 prefix. Add a version only when a breaking change is unavoidable. Put each version's resource class in its own namespace (Http\Resources\V2\OrderResource), and share the use case.
Input and output
Input: parse, validate, map to a command Must-know
In plain words: check the shape of the input at the door, convert it into the types your code wants, and only then let it in.
Common misunderstanding: "Client-side validation is enough" or "I can validate in the model." Client validation is a convenience; anyone can send a hand-made request. And model-level validation alone gives poor field-level errors for forms and API clients. There are two layers: boundary validation (format, types, required) in the Form Request or decode step, and domain validation (business invariants) in the use case.
Definition: a Form Request (Laravel) is a class that holds authorize(), rules(), optional prepareForValidation(), and returns validated() data (only keys that passed). In Go the equivalent is a decode function (json.Decoder with DisallowUnknownFields, r.ParseForm) followed by explicit checks. Both end by building a command for the use case.
Raw request Boundary Use case
1 customer="", total="abc" rules fail -> 422 + field errors (not called)
2 customer="Ada", total="12.50" total -> 1250 cents; valid Create(Ada, 1250)
3 customer="Ada", total_cents=-5 boundary ok (integer) rule fails: ValidationError -> 422Real scenarios: a signup form; a bulk import endpoint; an API called by a mobile app with a mistyped field; an attacker adding is_admin=1 (mass assignment; validated() or an explicit DTO keeps unknown fields out).
| Check | Where | Laravel | Go |
|---|---|---|---|
| Is it valid JSON, are fields of the right type | Boundary | Form Request rules, postJson | json.Decoder, DisallowUnknownFields |
| Body size | Boundary | Server config, middleware | http.MaxBytesReader |
| Is the user allowed | Boundary, then domain | authorize(), Policy | Middleware, explicit check |
| Is the customer on hold | Domain | In the action or a domain service | In Service.Create |
| Unknown or extra fields | Boundary | validated() or safe()->only() | DisallowUnknownFields |
| CSRF | Middleware | VerifyCsrfToken and @csrf | A CSRF middleware library, or http.CrossOriginProtection (Go 1.25 and later) |
Fix / how to use it. See StoreOrderRequest and the parseTotal function in the lab. The rule of thumb: the controller never reads $request->all(); it reads validated().
Output: view models, presenters, serializers Must-know
In plain words: one use case result can be shown as HTML, JSON or a CSV; each format has its own code that knows the format and nothing else.
Common misunderstanding: "The use case should return the final response." Then the use case imports an HTTP library. Clean Architecture's answer is a presenter: "the use case needs to call the presenter. However, this call must not be direct... So we have the use case call an interface (Use Case Output Port) in the inner circle, and have the presenter in the outer circle implement it."
Definition: a presenter converts the use case's result into a view model or response; a serializer (Laravel resource, Go encoder with a DTO) converts it to a wire format; a view renders the view model. In most web apps the controller plays the presenter's role in a few lines and that is fine, as long as the use case does not know it.
Use case result Presenter / serializer Response
1 []Order toRows -> []OrderRow HTML via template
2 []Order toJSON -> {"data":[...]} application/json
3 []Order csv writer text/csv
4 ValidationError form errors / 422 body re-rendered form / JSONReal scenarios: the same list as HTML for the browser and CSV for finance; error messages translated per locale in the presenter, not in the domain.
| Output form | Content negotiation | Laravel | Go |
|---|---|---|---|
| HTML page | Accept: text/html | view() | ExecuteTemplate |
| JSON | Accept: application/json | Resource, response()->json() | json.NewEncoder(w).Encode |
| Redirect after POST | 303 See Other | redirect()->route() | http.Redirect(..., 303) |
| Validation failure | 422 Unprocessable Content | Automatic for JSON requests | Explicit WriteHeader(422) |
| File download | Content-Disposition | response()->streamDownload() | http.ServeContent |
Fix / how to use it. One use case, one mapping function per representation, no shared formatting helper that mixes them.
Thin controllers
Fat vs thin controllers Must-know
In plain words: a controller action should read like a table of contents: parse, call, respond.
Common misunderstanding: "Thin controllers mean putting everything in the model." That produces the fat model (a god class with 80 methods). The destination of moved code is a use case or domain service, not a bigger Eloquent class.
Definition: a fat controller validates, applies business rules, runs SQL, sends mail and formats output. A thin controller only translates between HTTP and the application: take validated data, call one use case, return one response. Laravel offers three tools for this: single-action controllers (a class with an __invoke method, for "particularly complex" actions), action classes (a plain class like CreateOrder shared by controllers, commands and jobs), and Form Requests. Go's equivalents are small handler functions that call a Service method.
Fat controller (before) Thin controller (after)
1 validate 12 fields inline StoreOrderRequest validates
2 check customer status, compute totals CreateOrder does it
3 DB::table(...)->insert(...) repository inside the action
4 Mail::raw(...) OrderPlaced event, queued listener
5 return back()->with(...) return redirect()->route(...)Real scenarios: a checkout controller whose method grows each sprint; the same "create order" needed by an API, a CSV import and a queue consumer; a controller test that needs mail faking, the database and five mocks.
| Symptom | Likely cause | Move |
|---|---|---|
| Action longer than about 20 lines | Business logic inside | Extract an action or service |
| Controller imports a mailer, a PDF library | Side effects in the HTTP layer | Event plus listener or job |
| Same logic in web and API controllers | Missing use case | Extract, call from both |
| Many unrelated methods in one controller | Several resources in one class | Split per resource; single-action for odd ones |
| Controller test needs the database for a rule | Rule in the wrong place | Unit-test the use case instead |
Fix / how to use it. Compare Before/OrdersController.php and After/OrdersController.php in Laravel, and before/main.go with web/server.go in Go. The refactoring moves are Extract Method, Extract Class and Move Method from Code Smells & Refactoring; the principle behind them is SRP.
Mechanics
Templating and escaping (XSS pointer) Must-know
In plain words: anything a user typed that you print into a page must be turned into harmless text first, or the browser will run it as code.
Common misunderstanding: "My validation rejects bad input, so escaping is unnecessary." Validation cannot know every future context; output encoding must match where the value lands (HTML text, attribute, URL, JavaScript). OWASP's guidance is to encode at output; validation is a second layer.
Definition: XSS (cross-site scripting) happens when untrusted data is emitted into a page without context-correct encoding. Blade's double-curly output is passed through PHP's htmlspecialchars by default, while the unescaped form ({!! !!}) is documented as dangerous for user-supplied content. Go's html/template goes further: "the escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts", and the package inserts the right escaper for each action at parse time. The full defence (CSP, cookie flags, sanitisation of intentional HTML) is on Security by Design.
Customer name stored Template Browser sees
1 <script>steal()</script> Blade double-curly / Go {{.}} <script>... shown as text
2 <script>steal()</script> Blade unescaped / text/template runs the script (stored XSS)
3 javascript:alert(1) in a URL html/template in href replaced by #ZgotmplZReal scenarios: a comment system; a profile "bio"; an order list with customer names (our lab); an admin panel that renders a user's display name; rich text from an editor that must be sanitised, not merely escaped.
| Engine | Default | How to opt out | Contextual |
|---|---|---|---|
| Blade | Escapes with htmlspecialchars | Unescaped echo syntax, HtmlString | HTML only; use Js::from for JavaScript data |
Go html/template | Escapes by context | Typed values like template.HTML | Yes: HTML, attribute, URL, JS, CSS |
Go text/template | No escaping | n/a | No: never use for HTML |
| Jinja2, Twig | Depends on configuration | safe filter or raw | Twig: configurable per strategy |
| React, Vue | Escaped by default | dangerouslySetInnerHTML, v-html | HTML text and attributes |
Fix / how to use it. Use the default escaped output everywhere; treat each opt-out as a code-review flag; pass JSON to JavaScript with Js::from (Laravel) or json.Marshal inside html/template's JS context (Go). The lab includes a test that fails if a <script> tag from user data reaches the page.
State in UI interaction: sessions, cookies, flash data Important
In plain words: HTTP forgets you after every request, so a UI that remembers (logged in, selected filter, "Order created" message) stores that memory somewhere on purpose.
Common misunderstanding: "Put UI state in the server session; it's safest." Session state makes servers stateful: a second instance does not have it unless the session store is shared, and two browser tabs overwrite each other. Prefer URL state (filters, page, sort in the query string), and keep sessions for identity and flash messages.
Definition: UI state is information that exists because of the interaction, not because of the business: current page, sort order, wizard step, unsaved form values, toast messages. Where it can live: the URL (shareable, bookmarkable), a cookie, the server session (cookie holds only a session ID), local storage, the client store (Redux), or a Livewire component (round-tripped). Flash data is session data available for exactly the next request, used to show "Order created." after a redirect. See Web Sessions, Cookies, Serialization & CORS.
Request Server session / URL
1 POST /orders valid -> create; session.flash("status","Order created.")
2 303 Location /orders
3 GET /orders flash read once; page shows message; flash removed
4 F5 (reload) no message, no duplicate order (Post/Redirect/Get)Real scenarios: a wizard that should survive a refresh (store step in the URL or database); an admin list whose filter should be shareable in a link; a multi-tab user editing two orders.
| Where UI state lives | Survives refresh | Shareable | Scales across servers | Laravel | Go |
|---|---|---|---|---|---|
| URL query | Yes | Yes | Yes | $request->query() | r.URL.Query() |
| Cookie | Yes | No | Yes | Cookie::queue, encrypted | http.SetCookie |
| Server session | Yes | No | Only with a shared store | session(), old(), flash | A session library (stdlib has none) |
| Client store | No (unless persisted) | No | Yes | Inertia shared props, Pinia | n/a |
| Component state | Per request round trip | No | Needs sticky or shared state | Livewire properties | n/a |
Fix / how to use it. Use Post/Redirect/Get after every successful write. Re-render the form with the user's input and per-field errors on failure (old() and @error in Blade; FormState and Errors in the Go page struct).
HTTP details the presentation layer owns Important
In plain words: status codes, redirects and headers are part of the user interface for programs and for browsers.
Common misunderstanding: "Return 200 with an error message in the body; the client reads the message." Clients, caches, proxies and monitoring read the status code first.
Definition: the controller maps outcomes to codes. The table is the contract used by both lab implementations.
Outcome HTML flow JSON flow
1 List ok 200 page 200 {"data":[...]}
2 Created 303 -> list (PRG) 201 + Location + {"data":{...}}
3 Input malformed 400 or re-render with errors 400 {"error":"invalid JSON body"}
4 Business rule failed 422 re-rendered form 422 {"errors":{field:message}}
5 Not logged in 302 to login 401
6 Not allowed 403 page 403
7 Unexpected failure 500 generic page 500 {"error":"internal error"}| Code | Meaning | Use in presentation |
|---|---|---|
| 200 OK | Success with body | List and show |
| 201 Created | New resource | API create, with Location |
| 204 No Content | Success, no body | API delete |
| 302 Found / 303 See Other | Redirect (303 forces GET) | Post/Redirect/Get |
| 400 Bad Request | Malformed request | Unparseable JSON |
| 401 Unauthorized | Not authenticated | API without token |
| 403 Forbidden | Authenticated, not allowed | Policy denied |
| 404 Not Found | Missing resource | Route model binding failure |
| 419 (Laravel) | CSRF token mismatch or expired session | Form submitted after session expiry |
| 422 Unprocessable Content | Valid syntax, failed validation | Form and API validation errors |
| 429 Too Many Requests | Rate limited | Throttle middleware |
| 500 / 503 | Server failure / unavailable | Generic error, never a stack trace |
Fix / how to use it. Centralise the mapping from domain errors to codes in one place (an exception handler in Laravel, a small writeError in Go) so every controller answers the same way. Error design is on Error & Exception Handling.
Eloquent and SQL behind a list screen Good to know
In plain words: the "orders list" you see is one query behind the scenes; a bad view can turn it into many.
Common misunderstanding: "The ORM hides the SQL, so the view cannot affect performance." A template that touches $order->customer->name for each row can run one query per row.
Definition: the query for the list page, shaped as the read side of the screen. Paging by id (keyset) scales better than OFFSET; see Pagination.
-- The list screen: newest first, one page, only the columns the view needs.
SELECT id, customer, total_cents, status, created_at
FROM orders
ORDER BY id DESC
LIMIT 15;
-- Next page (keyset): no OFFSET scan.
SELECT id, customer, total_cents, status, created_at
FROM orders
WHERE id < :last_seen_id
ORDER BY id DESC
LIMIT 15;Real scenarios: a dashboard joining orders and customers (eager-load or join once); an export that must stream rather than load everything.
| Approach | Queries for 15 rows with a customer name | Laravel | Go |
|---|---|---|---|
| Lazy access in the view | 1 + 15 | Default relation access | Query inside the template function |
| Eager loading | 2 | Order::with('customer') | One IN query, map in memory |
| Join into a read model | 1 | Query builder join, DTO | JOIN and scan into a row struct |
Fix / how to use it. The view model is built after the data is loaded; the template never queries. More in ORM Pitfalls.
Go
Before
One handler parses, validates, runs SQL, applies a rule and prints HTML by hand. It has a stored XSS hole, leaks database errors, and cannot be tested without a database.
// Package main is the "before" picture: one handler that parses input,
// validates, runs SQL, applies business rules and prints HTML by hand.
// It works, and it is the shape that cannot be tested without a database
// and cannot serve a second UI (JSON, CLI, mobile) without copy-paste.
package main
import (
"database/sql"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
var db *sql.DB // opened somewhere else; global state is part of the problem
func ordersHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
customer := r.FormValue("customer")
total, err := strconv.ParseFloat(r.FormValue("total"), 64)
if customer == "" || err != nil || total <= 0 {
http.Error(w, "bad input", http.StatusBadRequest) // no field-level errors
return
}
// Business rule and SQL live inside the HTTP handler.
_, err = db.Exec(
"INSERT INTO orders (customer, total_cents, status, created_at) VALUES ($1, $2, 'new', $3)",
customer, int64(total*100), time.Now())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) // leaks internals
return
}
http.Redirect(w, r, "/orders", http.StatusSeeOther)
return
}
rows, err := db.Query("SELECT id, customer, total_cents, status FROM orders ORDER BY id DESC")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var b strings.Builder
b.WriteString("<h1>Orders</h1><table>")
for rows.Next() {
var id, cents int64
var customer, status string
if err := rows.Scan(&id, &customer, ¢s, &status); err != nil {
continue
}
// Hand-built HTML with no escaping: a customer named
// "<script>..." runs in every visitor's browser (stored XSS).
fmt.Fprintf(&b, "<tr><td>%d</td><td>%s</td><td>%.2f</td><td>%s</td></tr>",
id, customer, float64(cents)/100, status)
}
b.WriteString("</table>")
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(b.String()))
}
func main() {
http.HandleFunc("/orders", ordersHandler)
_ = http.ListenAndServe(":8080", nil)
}After
Four small pieces. order is the domain and use case (no HTTP). web is the delivery layer: handlers, a view model, a template and a JSON DTO. mvp and flux show the two other presentation shapes on the same use case.
The use case and its port:
// Package order is the domain and use-case layer. It knows nothing about
// HTTP, HTML, JSON or templates: that is what lets one use case serve a web
// page, a JSON API and a CLI.
package order
import (
"context"
"strings"
"time"
)
// Status is the order lifecycle state.
type Status string
// Order statuses.
const (
StatusNew Status = "new"
StatusPaid Status = "paid"
)
// Order is the domain entity.
type Order struct {
ID int64
Customer string
TotalCents int64
Status Status
CreatedAt time.Time
}
// CreateInput is the command a delivery mechanism hands to the use case.
// It is already parsed: cents are integers, strings are trimmed by the caller.
type CreateInput struct {
Customer string
TotalCents int64
}
// ValidationError maps a field name to a message. Delivery layers translate
// it to a 422 JSON body, a re-rendered form, or a CLI error.
type ValidationError map[string]string
// Error implements the error interface.
func (v ValidationError) Error() string {
parts := make([]string, 0, len(v))
for field, msg := range v {
parts = append(parts, field+": "+msg)
}
return "validation failed: " + strings.Join(parts, "; ")
}
// Repository is the port the use case needs; adapters implement it.
type Repository interface {
List(ctx context.Context) ([]Order, error)
Insert(ctx context.Context, o Order) (Order, error)
}
// Service holds the use cases.
type Service struct {
repo Repository
now func() time.Time
}
// NewService wires the use cases to a repository and a clock.
func NewService(repo Repository, now func() time.Time) *Service {
return &Service{repo: repo, now: now}
}
// List returns orders, newest first.
func (s *Service) List(ctx context.Context) ([]Order, error) {
return s.repo.List(ctx)
}
// Create enforces the business invariants (not the input format: parsing
// "12.50" into cents is the delivery layer's job).
func (s *Service) Create(ctx context.Context, in CreateInput) (Order, error) {
errs := ValidationError{}
if strings.TrimSpace(in.Customer) == "" {
errs["customer"] = "required"
}
if in.TotalCents <= 0 {
errs["total"] = "must be greater than zero"
}
if len(errs) > 0 {
return Order{}, errs
}
return s.repo.Insert(ctx, Order{
Customer: in.Customer,
TotalCents: in.TotalCents,
Status: StatusNew,
CreatedAt: s.now().UTC(),
})
}The in-memory adapter used by tests and the lab:
package order
import (
"context"
"sync"
)
// MemoryRepo is an in-memory Repository for tests and the lab.
type MemoryRepo struct {
mu sync.Mutex
next int64
items []Order
}
// List returns orders newest first.
func (m *MemoryRepo) List(_ context.Context) ([]Order, error) {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]Order, len(m.items))
for i, o := range m.items {
out[len(m.items)-1-i] = o
}
return out, nil
}
// Insert assigns an ID and stores the order.
func (m *MemoryRepo) Insert(_ context.Context, o Order) (Order, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.next++
o.ID = m.next
m.items = append(m.items, o)
return o, nil
}The handlers (front controller routes, HTML flow, JSON flow):
// Package web is the delivery layer (Clean Architecture: interface
// adapters). Handlers do four things: parse, call a use case, map the
// result to a representation, write the response. Nothing else.
package web
import (
"embed"
"encoding/json"
"errors"
"html/template"
"net/http"
"time"
"academy/mvc/order"
)
//go:embed templates/*.html
var templateFS embed.FS
// Server serves the same use cases as an HTML page and as a JSON API.
type Server struct {
orders *order.Service
tpl *template.Template
}
// New parses the templates once at start-up; a broken template fails fast.
func New(orders *order.Service) (*Server, error) {
tpl, err := template.ParseFS(templateFS, "templates/*.html")
if err != nil {
return nil, err
}
return &Server{orders: orders, tpl: tpl}, nil
}
// Routes is the front controller: one mux, one place for cross-cutting
// middleware: wrap the returned handler to add logging, auth or recovery.
func (s *Server) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /orders", s.listHTML)
mux.HandleFunc("POST /orders", s.createHTML)
mux.HandleFunc("GET /api/v1/orders", s.listJSON)
mux.HandleFunc("POST /api/v1/orders", s.createJSON)
return mux
}
// ---- HTML (server-rendered MVC) ----
func (s *Server) listHTML(w http.ResponseWriter, r *http.Request) {
orders, err := s.orders.List(r.Context())
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
s.render(w, http.StatusOK, OrdersPage{Rows: toRows(orders)})
}
func (s *Server) createHTML(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
form := FormState{Customer: r.PostFormValue("customer"), Total: r.PostFormValue("total")}
errs := map[string]string{}
cents, err := parseTotal(form.Total)
if err != nil {
errs["total"] = "must be a number" // boundary validation: format
}
if len(errs) == 0 {
_, err = s.orders.Create(r.Context(), order.CreateInput{Customer: form.Customer, TotalCents: cents})
var ve order.ValidationError
switch {
case err == nil:
http.Redirect(w, r, "/orders", http.StatusSeeOther) // Post/Redirect/Get
return
case errors.As(err, &ve):
errs = ve // domain validation: business rules
default:
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
}
orders, _ := s.orders.List(r.Context())
s.render(w, http.StatusUnprocessableEntity, OrdersPage{Rows: toRows(orders), Form: form, Errors: errs})
}
func (s *Server) render(w http.ResponseWriter, status int, page OrdersPage) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
// html/template escapes by context: text, attribute, URL, JS.
if err := s.tpl.ExecuteTemplate(w, "orders.html", page); err != nil {
http.Error(w, "render error", http.StatusInternalServerError)
}
}
// ---- JSON (API-first representation) ----
// orderJSON is the wire DTO. It is versioned by the URL (/api/v1) and is
// deliberately NOT the domain type: renaming a domain field must not break
// mobile clients.
type orderJSON struct {
ID int64 `json:"id"`
Customer string `json:"customer"`
TotalCents int64 `json:"total_cents"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
type createRequest struct {
Customer string `json:"customer"`
TotalCents int64 `json:"total_cents"`
}
func toJSON(o order.Order) orderJSON {
return orderJSON{o.ID, o.Customer, o.TotalCents, string(o.Status), o.CreatedAt}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func (s *Server) listJSON(w http.ResponseWriter, r *http.Request) {
orders, err := s.orders.List(r.Context())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
return
}
data := make([]orderJSON, 0, len(orders)) // [] not null for empty lists
for _, o := range orders {
data = append(data, toJSON(o))
}
writeJSON(w, http.StatusOK, map[string]any{"data": data})
}
func (s *Server) createJSON(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var in createRequest
if err := dec.Decode(&in); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
return
}
o, err := s.orders.Create(r.Context(), order.CreateInput{Customer: in.Customer, TotalCents: in.TotalCents})
var ve order.ValidationError
switch {
case err == nil:
w.Header().Set("Location", "/api/v1/orders")
writeJSON(w, http.StatusCreated, map[string]any{"data": toJSON(o)})
case errors.As(err, &ve):
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"errors": ve})
default:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}
}The view model and the input parser:
package web
import (
"fmt"
"math"
"strconv"
"strings"
"academy/mvc/order"
)
// OrderRow is the view model for one table row: everything is already a
// display string, so the template contains no logic beyond loops and ifs.
type OrderRow struct {
ID int64
Customer string
Total string // "12.50"
Status string // human label
Created string // "2026-11-25 10:00"
CanPay bool
}
// OrdersPage is the view model for the whole screen, including the form
// state needed to re-render after a validation error.
type OrdersPage struct {
Rows []OrderRow
Form FormState
Errors map[string]string
}
// FormState keeps what the user typed so a failed submit does not erase it.
type FormState struct {
Customer string
Total string
}
func toRows(orders []order.Order) []OrderRow {
rows := make([]OrderRow, 0, len(orders))
for _, o := range orders {
rows = append(rows, OrderRow{
ID: o.ID,
Customer: o.Customer,
Total: formatCents(o.TotalCents),
Status: strings.ToUpper(string(o.Status)),
Created: o.CreatedAt.Format("2006-01-02 15:04"),
CanPay: o.Status == order.StatusNew,
})
}
return rows
}
func formatCents(c int64) string {
return fmt.Sprintf("%d.%02d", c/100, c%100)
}
// parseTotal converts user text such as "12.50" into integer cents. This is
// input-format work (boundary), not a business rule. Simplified: it accepts
// at most two decimals and uses float rounding for brevity.
func parseTotal(s string) (int64, error) {
f, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) {
return 0, fmt.Errorf("not a number")
}
return int64(math.Round(f * 100)), nil
}The template (html/template escapes by context):
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Orders</title></head>
<body>
<h1>Orders</h1>
<form method="post" action="/orders">
<label>Customer <input name="customer" value="{{.Form.Customer}}"></label>
{{with .Errors.customer}}<span class="error">{{.}}</span>{{end}}
<label>Total <input name="total" value="{{.Form.Total}}"></label>
{{with .Errors.total}}<span class="error">{{.}}</span>{{end}}
<button>Create order</button>
</form>
<table>
<tr><th>#</th><th>Customer</th><th>Total</th><th>Status</th><th>Created</th></tr>
{{range .Rows}}
<tr>
<td>{{.ID}}</td>
<td>{{.Customer}}</td>
<td>{{.Total}}</td>
<td>{{.Status}}</td>
<td>{{.Created}}</td>
</tr>
{{else}}
<tr><td colspan="5">No orders yet.</td></tr>
{{end}}
</table>
</body>
</html>The composition root:
// Command server wires the layers together: the composition root is the
// only place that knows every concrete type.
package main
import (
"log"
"net/http"
"time"
"academy/mvc/order"
"academy/mvc/web"
)
func main() {
svc := order.NewService(&order.MemoryRepo{}, time.Now)
srv, err := web.New(svc)
if err != nil {
log.Fatal(err)
}
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", srv.Routes()))
}The Go angle
Go has no MVC framework in the standard library, and does not need one. net/http supplies the front controller (http.Server, ServeMux with patterns such as "GET /orders" that match method, host and path), html/template supplies contextual escaping, encoding/json supplies serialisation, and httptest supplies tests. The usual layering is handler, then service, then repository: the handler is the controller, the service is the use case, the repository is the gateway. Go idioms to keep:
- Keep the domain package free of
net/http; acceptcontext.Contextand return typed errors the handler can switch on witherrors.As. - Parse templates once at start-up (
template.ParseFSwithgo:embed); a broken template should stop the process, not the first request. - Use
json:"..."DTO structs, not domain types, for the wire; initialise slices withmakeso empty lists encode as[]. - Prefer
json.DecoderwithDisallowUnknownFieldsandhttp.MaxBytesReaderfor request bodies. - Middleware is a function that wraps a
http.Handler; compose it aroundRoutes(). - For the second UI shape, a Passive View presenter and a reducer are plain packages:
// Package mvp shows the Passive View variant of Model-View-Presenter. The
// view is an interface with no logic; every decision lives in the presenter,
// so the whole screen behaviour is testable without a UI toolkit.
package mvp
import (
"context"
"errors"
"strconv"
"strings"
"academy/mvc/order"
)
// Row is what the view is told to display.
type Row struct {
ID int64
Customer string
Total string
}
// View is implemented by a GUI, a TUI, or a test fake. It only displays.
type View interface {
ShowOrders(rows []Row)
ShowFieldError(field, message string)
ClearForm()
}
// Orders is the use-case port the presenter depends on.
type Orders interface {
List(ctx context.Context) ([]order.Order, error)
Create(ctx context.Context, in order.CreateInput) (order.Order, error)
}
// Presenter reacts to user events and drives the view.
type Presenter struct {
view View
orders Orders
}
// New binds a presenter to a view.
func New(v View, o Orders) *Presenter { return &Presenter{view: v, orders: o} }
// OnLoad is called when the screen appears.
func (p *Presenter) OnLoad(ctx context.Context) error {
list, err := p.orders.List(ctx)
if err != nil {
return err
}
rows := make([]Row, 0, len(list))
for _, o := range list {
rows = append(rows, Row{o.ID, o.Customer, strconv.FormatFloat(float64(o.TotalCents)/100, 'f', 2, 64)})
}
p.view.ShowOrders(rows)
return nil
}
// OnSubmit is called when the user presses "Create".
func (p *Presenter) OnSubmit(ctx context.Context, customer, total string) error {
f, err := strconv.ParseFloat(strings.TrimSpace(total), 64)
if err != nil {
p.view.ShowFieldError("total", "must be a number")
return nil
}
_, err = p.orders.Create(ctx, order.CreateInput{Customer: customer, TotalCents: int64(f * 100)})
var ve order.ValidationError
if errors.As(err, &ve) {
for field, msg := range ve {
p.view.ShowFieldError(field, msg)
}
return nil
}
if err != nil {
return err
}
p.view.ClearForm()
return p.OnLoad(ctx)
}// Package flux is a tiny unidirectional data flow: Action -> Reduce -> State
// -> View. State is only ever replaced by Reduce, a pure function, so every
// screen state can be reproduced by replaying actions.
package flux
import (
"sync"
"academy/mvc/order"
)
// State is the single source of truth for the orders screen.
type State struct {
Orders []order.Order
Loading bool
Error string
}
// Action describes something that happened; it carries data, not behaviour.
type Action interface{ isAction() }
// LoadRequested means the user opened the screen.
type LoadRequested struct{}
// OrdersLoaded carries the server response.
type OrdersLoaded struct{ Orders []order.Order }
// LoadFailed carries a user-safe message.
type LoadFailed struct{ Message string }
func (LoadRequested) isAction() {}
func (OrdersLoaded) isAction() {}
func (LoadFailed) isAction() {}
// Reduce is pure: same state and action in, same state out, no I/O.
func Reduce(s State, a Action) State {
switch act := a.(type) {
case LoadRequested:
return State{Orders: s.Orders, Loading: true}
case OrdersLoaded:
return State{Orders: act.Orders}
case LoadFailed:
return State{Orders: s.Orders, Error: act.Message}
default:
return s
}
}
// Store holds the state and notifies subscribers (the "views") after each
// action. Views never write to the state directly.
type Store struct {
mu sync.Mutex
state State
subs []func(State)
}
// Subscribe registers a view callback.
func (s *Store) Subscribe(f func(State)) {
s.mu.Lock()
defer s.mu.Unlock()
s.subs = append(s.subs, f)
}
// Dispatch is the only way to change state.
func (s *Store) Dispatch(a Action) {
s.mu.Lock()
s.state = Reduce(s.state, a)
st, subs := s.state, append([]func(State){}, s.subs...)
s.mu.Unlock()
for _, f := range subs {
f(st)
}
}Laravel
Before
A controller that validates by hand, writes SQL, sends mail and formats display values. It works, and the mobile app's API would have to copy all of it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
// A fat controller: it validates, applies business rules, writes SQL, sends
// mail and builds the view data. The web page works; the JSON API for the
// mobile app would have to copy all of it.
class OrdersController extends Controller
{
public function index()
{
$orders = DB::table('orders')->orderByDesc('id')->get();
// Presentation formatting mixed into the controller.
foreach ($orders as $o) {
$o->total = number_format($o->total_cents / 100, 2);
$o->status_label = strtoupper($o->status);
}
return view('orders.index', ['orders' => $orders]);
}
public function store(Request $request)
{
if (! $request->customer || (float) $request->total <= 0) {
return back()->with('error', 'Bad input'); // no field-level errors, old input lost
}
$id = DB::table('orders')->insertGetId([
'customer' => $request->customer,
'total_cents' => (int) ((float) $request->total * 100),
'status' => 'new',
'created_at' => now(),
'updated_at' => now(),
]);
Mail::raw("Order #$id received", fn ($m) => $m->to('ops@example.com')->subject('New order'));
return redirect('/orders');
}
}After
The same screen split into the framework's slots. The three presentations share one Form Request and one action.
Boundary validation:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
// Boundary validation: shape and format of the input. Business invariants
// ("a customer on hold cannot order") belong to the use case, not here.
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
// Authorization is part of the boundary too: swap for a Policy check
// (`$this->user()->can('create', Order::class)`) when roles exist.
return $this->user() !== null;
}
/** @return array<string, array<int, string>> */
public function rules(): array
{
return [
'customer' => ['required', 'string', 'max:120'],
'total_cents' => ['required', 'integer', 'min:1'],
];
}
// Web form posts "12.50"; convert once at the boundary, before validation.
protected function prepareForValidation(): void
{
if ($this->has('total') && ! $this->has('total_cents') && is_numeric($this->input('total'))) {
$this->merge(['total_cents' => (int) round(((float) $this->input('total')) * 100)]);
}
}
}The use case:
<?php
namespace App\Actions;
use App\Enums\OrderStatus;
use App\Events\OrderPlaced;
use App\Models\Order;
// The use case: no Request, no Response, no view. Called from a controller,
// an Artisan command, a queued job or a test with the same arguments.
final class CreateOrder
{
public function __invoke(string $customer, int $totalCents): Order
{
$order = Order::create([
'customer' => $customer,
'total_cents' => $totalCents,
'status' => OrderStatus::New,
]);
// Side effects are events, not controller code.
OrderPlaced::dispatch($order);
return $order;
}
}The Blade controller and its view:
<?php
namespace App\Http\Controllers;
use App\Actions\CreateOrder;
use App\Http\Requests\StoreOrderRequest;
use App\Models\Order;
use App\ViewModels\OrderRowViewModel;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
// Server-rendered MVC: the controller translates HTTP to a use case call and
// the result to a view. Each action is a handful of lines.
class OrdersController extends Controller
{
public function index(): View
{
$orders = Order::query()->latest('id')->paginate(15);
return view('orders.index', [
'rows' => $orders->getCollection()->map(OrderRowViewModel::from(...)),
'orders' => $orders, // for ->links()
]);
}
public function store(StoreOrderRequest $request, CreateOrder $createOrder): RedirectResponse
{
$data = $request->validated(); // only validated keys, never ->all()
$createOrder($data['customer'], $data['total_cents']);
return redirect()->route('orders.index')->with('status', 'Order created.');
}
}{{-- resources/views/orders/index.blade.php --}}
<x-layout title="Orders">
@if (session('status'))
<p class="flash">{{ session('status') }}</p>
@endif
<form method="POST" action="{{ route('orders.store') }}">
@csrf
<label>Customer
<input name="customer" value="{{ old('customer') }}">
</label>
@error('customer') <span class="error">{{ $message }}</span> @enderror
<label>Total
<input name="total" value="{{ old('total') }}">
</label>
@error('total_cents') <span class="error">{{ $message }}</span> @enderror
<button>Create order</button>
</form>
<table>
<tr><th>#</th><th>Customer</th><th>Total</th><th>Status</th><th>Created</th></tr>
@forelse ($rows as $row)
<tr>
<td>{{ $row->id }}</td>
{{-- {{ }} runs htmlspecialchars; {!! !!} would not --}}
<td>{{ $row->customer }}</td>
<td>{{ $row->total }}</td>
<td>{{ $row->status }}</td>
<td>{{ $row->created }}</td>
</tr>
@empty
<tr><td colspan="5">No orders yet.</td></tr>
@endforelse
</table>
{{ $orders->links() }}
</x-layout>The view model for the Blade page:
<?php
namespace App\ViewModels;
use App\Models\Order;
// A view model for the Blade page: display strings are computed here, so the
// template stays free of formatting logic and the formatting is unit-testable.
final readonly class OrderRowViewModel
{
public function __construct(
public int $id,
public string $customer,
public string $total,
public string $status,
public string $created,
) {}
public static function from(Order $order): self
{
return new self(
id: $order->id,
customer: $order->customer,
total: number_format($order->total_cents / 100, 2),
status: $order->status->label(),
created: $order->created_at->format('Y-m-d H:i'),
);
}
}The API resource and controller:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
// The API representation: a stable, versioned contract. It is NOT the Eloquent
// model: columns can be renamed or added without breaking mobile clients.
/** @mixin \App\Models\Order */
class OrderResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'customer' => $this->customer,
'total_cents' => $this->total_cents,
'status' => $this->status->value,
'created_at' => $this->created_at->toIso8601String(),
];
}
}<?php
namespace App\Http\Controllers\Api\V1;
use App\Actions\CreateOrder;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
// API-first presentation: same use case, JSON representation, status codes.
class OrderApiController extends Controller
{
public function index(): AnonymousResourceCollection
{
// Paginated resource collections add "links" and "meta" automatically.
return OrderResource::collection(Order::query()->latest('id')->paginate(15));
}
public function store(StoreOrderRequest $request, CreateOrder $createOrder): JsonResponse
{
$data = $request->validated();
$order = $createOrder($data['customer'], $data['total_cents']);
return (new OrderResource($order))
->response()
->setStatusCode(201)
->header('Location', route('api.v1.orders.index'));
}
}The Inertia stub:
<?php
namespace App\Http\Controllers;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Inertia\Inertia;
use Inertia\Response;
// Inertia stub (composer require inertiajs/inertia-laravel): the controller
// stays a controller, but the "view" is a JavaScript page component. The
// props are the same resource the API returns, so the contract is shared.
// Creating an order reuses OrdersController::store: same Form Request, same
// action, same redirect; Inertia follows the 303 and re-renders the page.
class OrdersInertiaController extends Controller
{
public function index(): Response
{
return Inertia::render('Orders/Index', [
'orders' => OrderResource::collection(
Order::query()->latest('id')->paginate(15)
),
]);
}
}Routes, model, enum, event and migration:
<?php
use App\Http\Controllers\Api\V1\OrderApiController;
use App\Http\Controllers\OrdersController;
use App\Http\Controllers\OrdersInertiaController;
use Illuminate\Support\Facades\Route;
// ---- routes/web.php ----
Route::middleware(['auth'])->group(function () {
// Blade version
Route::get('/orders', [OrdersController::class, 'index'])->name('orders.index');
Route::post('/orders', [OrdersController::class, 'store'])->name('orders.store');
// Inertia version of the same screen
Route::get('/app/orders', [OrdersInertiaController::class, 'index'])->name('app.orders.index');
});
// ---- routes/api.php (enable with: php artisan install:api; mounted under /api) ----
Route::prefix('v1')->name('api.v1.')->middleware('auth:sanctum')->group(function () {
Route::get('/orders', [OrderApiController::class, 'index'])->name('orders.index');
Route::post('/orders', [OrderApiController::class, 'store'])->name('orders.store');
});<?php
namespace App\Models;
use App\Enums\OrderStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory;
protected $fillable = ['customer', 'total_cents', 'status'];
protected function casts(): array
{
return [
'status' => OrderStatus::class,
'total_cents' => 'integer',
];
}
}<?php
namespace App\Enums;
enum OrderStatus: string
{
case New = 'new';
case Paid = 'paid';
public function label(): string
{
return strtoupper($this->value);
}
}<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
// A plain event; a queued listener sends the mail, so the HTTP response
// does not wait for SMTP.
final class OrderPlaced
{
use Dispatchable;
public function __construct(public readonly Order $order) {}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('customer');
$table->unsignedBigInteger('total_cents');
$table->string('status')->default('new');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('orders');
}
};The Laravel angle
Laravel's slots map onto the patterns on this page:
| Pattern part | Laravel feature | Notes |
|---|---|---|
| Front controller | HTTP kernel, routes/web.php, routes/api.php, middleware | api.php is enabled with php artisan install:api |
| Page controller | Controller class; single-action controllers via __invoke | The docs recommend single-action for "particularly complex" actions |
| Input boundary | FormRequest: authorize(), rules(), prepareForValidation(), validated(), safe() | Use validated(), never all() |
| Use case | Action class (your own convention) | Laravel has no mandated folder |
| View model | Readonly class, or data from a view composer (View::composer) | Composers run each time the view renders |
| HTML view | Blade; components; @error, old(), @csrf | Escaped output by default |
| JSON view | JsonResource, ResourceCollection, toResource() (and the UseResource attribute) | Pagination adds links and meta |
| SPA bridge | Inertia (Inertia::render), starter kits | Server keeps routing and auth |
| Reactive server UI | Livewire components (wire:model, wire:click) | State round-trips to the server |
| Tests | get, post, postJson, assertOk, assertJsonStructure, assertViewHas, assertInertia | assertInertia comes from the Inertia package |
A short Livewire sketch of the same screen (not run here): the component class holds $customer and $total, a create() method that validates with #[Validate] or $this->validate() and calls the same CreateOrder action, and a render() that returns the Blade view with OrderRowViewModel rows. Livewire's docs show wire:model binding an input to a public property and wire:click calling a method, with state kept on the server.
Solving the classic problems
| Problem | Symptom | Solution | Cost |
|---|---|---|---|
| Fat controller | Action of 100+ lines | Form Request, action class, event | More files |
| Leaking model to view or API | Column rename breaks clients; hidden fields exposed | Resource or DTO | Mapping code |
| N+1 in the view | Query count grows with rows | Eager load, read model | Care at load time |
| Logic in templates | @if ($o->total > 100 && ...) | View model boolean | One more class |
| Double submit | Two orders on double click or refresh | PRG, idempotency key, disabled button | Key storage |
| Lost user input on error | Form empties after 422 | Re-render with old input | Slightly more code |
| Unversioned API | Breaking change hurts old mobile build | Version prefix, additive changes | Parallel resources |
| Duplicate validation | Rules differ between web and API | One Form Request or shared rules | Shared class |
| Presenter in the domain | Use case imports net/http or a template engine | Output port implemented by the adapter | An interface |
| Unescaped output | Stored XSS | Default escaping, test for it | None |
Fat controller
Extract the work in four moves: validation to a Form Request, the rule and the write to an action class, the mail to an event and a queued listener, the display formatting to a view model. Keep a controller test that checks only the translation (status code, redirect, rendered data), and move rule tests to the action. See the Laravel section for the end state.
N+1 in the view
Template loop Queries
1 SELECT * FROM orders LIMIT 15 1
2 row 1: $order->customer->name SELECT * FROM customers WHERE id = ? (2)
3 row 2: $order->customer->name another SELECT (3)
4 ... row 15 total: 16 queries
5 with('customer') eager load total: 2 queriesIn Laravel call Order::with('customer'); and call Model::preventLazyLoading(! app()->isProduction()) in a service provider so an accidental lazy load throws during development (documented on the Eloquent relationships page). In Go the same bug is a template function that queries per row; the fix is to load the data before rendering.
Double submit
User Server
1 click Create (slow) POST /orders -> order #1 created, 303
2 click Create again POST /orders -> order #2 created (bug)
3 with Idempotency-Key: k1 POST -> order #1; second POST with k1 -> returns order #1Disable the button after the first click (UX only), redirect after POST (PRG) so a refresh does not resubmit, and for APIs use an idempotency key stored with a unique constraint. See API Idempotency.
Validation duplicated in web and API
Use one Form Request for both the Blade and API controllers (as the lab does), with prepareForValidation() converting the web form's total into total_cents. In Go, call one parse function and one Service.Create; the handlers differ only in how they read the body and write the response.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Content site or admin, small team | Server-rendered MVC (Blade, html/template) | HTMX for small interactions | Fewest moving parts |
| Rich interactive admin, backend-heavy team | Livewire | Alpine for client details | One language, server owns state |
| Existing Vue or React team, one web client | Inertia | Resources as props | Keeps Laravel routing and auth |
| Mobile app plus web plus partners | API-first with versioned resources | OpenAPI contract, contract tests | One contract, many clients |
| Large client-side state (editor, canvas, offline) | SPA with Redux-style store | Optimistic updates | State logic belongs in the client |
| Desktop or terminal UI in Go | Passive View presenter or Elm-style model | Fake view in tests | Testable without a toolkit |
| Windows or .NET desktop | MVVM with binding | Commands, INotifyPropertyChanged | Native support |
| Different needs per client (mobile vs web) | BFF per client | Shared downstream services | Tailored payloads |
| Many teams on one huge front end | Micro-frontends | Shared design system | Independent deploys, with a cost |
| Three-field form | One handler, no extra layers | Keep rules in one function | Layers must pay for themselves |
In architecture: from a single process to a distributed system
Where MVC sits in Clean and Hexagonal architecture
Clean Architecture is explicit about it: the interface-adapters ring is "this layer, for example, that will wholly contain the MVC architecture of a GUI. The Presenters, Views, and Controllers all belong in here." Dependencies point inward: controller calls the use case through an input port; the use case reports through an output port that the presenter implements. In Hexagonal terms the controller is a driving adapter and the repository is a driven adapter.
See Dependency Inversion for the rule that makes this work, and Data Persistence in Design for the driven side.
Monolith: one process, one database
How it shows up: controllers, views and actions in one codebase.
Simplest correct usage: Form Request, action, Blade; or handler, service, template in Go; one composition root.
Example (simple): a blog: PostController calls PublishPost, redirects with a flash message; the list page renders PostRowViewModel.
Example (production): a shop's order screen: the Blade page, the mobile API (/api/v1/orders) and an Artisan import command all call CreateOrder; the list view model formats money once; tests cover the action by unit test and each presentation by one feature test.
Modular monolith and multiple databases
How it shows up: each module owns its use cases and exposes a facade; presentation can be per module (a module's controllers and views) or in a shared "web" shell that composes modules.
Rules: a controller calls its own module's actions only; cross-module data arrives through a facade or an event, not by querying the other module's tables; view composers may assemble shared layout data, but must call facades, not models. See Modular Monolith.
Page /dashboard Modules (each with its own tables)
1 DashboardController calls Orders::recent(5), Billing::balance(), Support::openTickets()
2 builds DashboardViewModel from three facades; no cross-schema joins
3 Blade renders three panels each panel survives if one module is slow (timeouts, fallbacks)Microservices: UI composition across services
What survives: the use case inside each service. What changes: the UI needs data from several services, so someone has to compose it.
| Composition style | Where it runs | Good for | Costs |
|---|---|---|---|
| API gateway composition | Gateway, server side | Simple fan-out, same shape for all clients | One shape fits no client perfectly |
| BFF (Backend for Frontend) | One server-side backend per user experience | Different payloads for web, iOS, partners | More services to run; one team per BFF |
| GraphQL gateway | Server | Client-chosen fields | Query cost, caching |
| Server-side includes / ESI | Edge or server | Fragment pages | Fragment latency |
| Micro-frontends | Browser or edge | Many teams, one page | Duplicate dependencies, shared design system needed |
Sam Newman's description of BFF is useful: rather than a general-purpose API backend, "you have one backend per user experience", and "the BFF is tightly coupled to a specific user experience, and will typically be maintained by the same team as the user interface." Fowler's micro-frontend article describes the same pressure from the other side: scaling frontend development "so that many teams can work simultaneously on a large and complex product."
Mobile app mobile-bff orders-svc billing-svc
1 GET /home -> fan-out in parallel --> GET /orders?me GET /balance
2 merge, trim fields <-- results <-- results
3 <- one small payload (timeouts, fallbacks if billing is slow)Example (production): a checkout page shows items from orders-svc, price from pricing-svc and a delivery estimate from shipping-svc. A web BFF calls all three with a 300 ms timeout each and a fallback ("estimate unavailable") so one slow service does not blank the page. The BFF also owns session cookies and CSRF, keeping the services free of browser concerns. Resilience patterns for the fan-out are on Distribution of Components; the gateway and BFF at architecture scale are on API Gateway, BFF & Service Mesh.
Distributed data: replicas, caches and eventual consistency
Where presentation breaks: after a write, the next page reads from a replica that has not caught up; the user sees the old list ("where is my order?").
| Problem | Presentation-level fix |
|---|---|
| Replica lag after redirect | Read from the primary for a short time after a write (sticky session or a flag in the redirect), or show the created item from the POST response |
| Stale cache of a rendered fragment | Short TTL, key by version, invalidate on events |
| Eventually consistent projections | UI says "processing", polls or subscribes (SSE, WebSocket); do not show a stale value as final |
| Optimistic UI (client store) | Apply the action locally, reconcile with the server result, roll back on error |
| Multiple tabs / devices | Server state is the truth; client store refreshes on focus |
See Real-Time Communication for push channels and Replication & Failover for lag.
Scaling path: 1×, 10×, 100×
| Scale | Structure | Presentation practice |
|---|---|---|
| 1× (one team, one app) | Server-rendered MVC, thin controllers | Form Request, action, view model; tests per presentation |
| 10× (several teams, one repo) | Modular monolith; API for mobile | Versioned resources, contract tests, per-module controllers |
| 100× (many teams, many clients) | Services plus BFFs; maybe micro-frontends | One BFF per experience, OpenAPI contracts, design system, CDN for static assets |
Testing presentation
HTTP tests, snapshot tests, contract tests Must-know
In plain words: test the rules once as plain functions, then test that each presentation translates correctly with a few HTTP-level checks.
Common misunderstanding: "To be safe, test everything through the browser." Browser tests are slow and flaky; they should cover a handful of journeys. Most presentation logic is testable with plain HTTP requests against the handler or router.
Definition: an HTTP test sends a request to the handler (Go: httptest.NewRecorder; Laravel: $this->get(), postJson()) and asserts status, headers and body. A snapshot test compares rendered output to a stored copy (useful for templates and serialised JSON; brittle if overused). A contract test pins the response shape that clients depend on (Laravel assertJsonStructure, an exact JSON string in Go, or schema validation against an OpenAPI file) and, in the consumer-driven form, lets each client publish the shape it needs.
Test type Input Assertion
1 Unit (use case) CreateInput{"",0} ValidationError with both fields
2 HTTP (HTML) POST /orders customer=<script> page contains <script>, not the tag
3 HTTP (JSON) GET /api/v1/orders body equals the stored contract
4 Snapshot render orders.html matches stored golden file (reviewed on change)
5 Presenter fake view + OnSubmit("", "0") view got errors, did not clear the form
6 Reducer replay [Load, Loaded] same state both timesReal scenarios: a refactor that renames a column but must not change the API; a template change that accidentally drops escaping; a client team that breaks when a field disappears.
| What | Go | Laravel |
|---|---|---|
| Use case | order_test.go plain test | Unit test of the action with RefreshDatabase |
| HTML flow | httptest + strings.Contains | get()->assertOk()->assertSee() |
| JSON contract | Compare exact JSON string | assertJsonStructure, assertJsonPath |
| Validation | Assert 422 and field message | assertSessionHasErrors, assertJsonValidationErrors |
| Inertia | n/a | assertInertia(fn ($page) => $page->component(...)->has(...)) |
| Presenter or view model | Fake view, reducer replay | Plain unit test on the view model |
Fix / how to use it. All Go tests in the lab run with go test ./...; the PHP tests in OrdersTest.php show the Laravel equivalents (reviewed, not run here).
Lab: one screen, many presentations
You build one "orders list plus create order" screen, check that every presentation shares one use case, and test it. The Go part runs offline.
Setup.
cd docs/snippets/design/interaction-presentation-mvc/go
gofmt -l . # no output
go vet ./... # clean
go test ./...
# ok academy/mvc/flux
# ok academy/mvc/mvp
# ok academy/mvc/order
# ok academy/mvc/webStep 1: read the "before" handler. Open before/main.go and list what it does: parsing, validation, SQL, rule, HTML. Expected: five jobs in one function, and a stored XSS hole in fmt.Fprintf(... %s ...).
Step 2: run the screen.
go run ./cmd/server &
curl -s -i -d 'customer=Ada&total=12.50' localhost:8080/orders # 303 Location: /orders
curl -s localhost:8080/orders | grep -o '<td>[^<]*</td>' | head # Ada, 12.50, NEW
curl -s -i -d 'customer=&total=abc' localhost:8080/orders | head -1 # HTTP/1.1 422 Unprocessable Entity
curl -s localhost:8080/api/v1/orders # {"data":[{"id":1,...}]}
curl -s -X POST -d '{"customer":"","total_cents":0}' localhost:8080/api/v1/orders # {"errors":{...}}
kill %1Step 3: prove the XSS defence.
curl -s -d 'customer=<script>alert(1)</script>&total=1' localhost:8080/orders >/dev/null
curl -s localhost:8080/orders | grep -c '<script>' # 1 (escaped)Now temporarily replace html/template with text/template in web/server.go and run go test ./web. Expected: TestHTMLEscapesUserContent fails with "unescaped script tag". Revert the change.
Step 4: add a second presentation without touching the domain. Add a GET /orders.csv handler that calls s.orders.List and writes CSV. Expected: git diff --stat touches only web/; order/ is unchanged. That is Separated Presentation measured.
Step 5: swap the delivery shape. Read mvp/presenter.go and mvp/presenter_test.go. Add a case: OnSubmit("Ada", " 12.50 ") must succeed. Expected: the test passes because the presenter trims input; the same use case serves a GUI.
Step 6: replay state. Read flux/store_test.go. Add LoadFailed{"timeout"} between the two actions and assert Error is reset by OrdersLoaded. Expected: Reduce returns a fresh State, so the error disappears.
Step 7 (Laravel, reviewed not run). In a fresh Laravel 13 app, copy the files from the Laravel section into place, run php artisan install:api, run the migration and php artisan test. Expected: five tests pass; the Inertia test requires composer require inertiajs/inertia-laravel.
| Metric | Before (fat handler/controller) | After (layers) |
|---|---|---|
| Jobs per controller action | 5 | 1 (translate) |
| Presentations sharing the rule | 1 (copy for each new one) | 3 (HTML, JSON, presenter) |
| Test of "total must be positive" needs | Database and HTTP | One plain function call |
| New output format touches the domain | Yes | No |
| XSS on customer name | Yes | No (test enforces it) |
| Files to read for one change | 1 (big) | 2 to 3 (small) |
Common misconceptions
| Belief | Reality |
|---|---|
| MVC is a folder structure | It is a rule about who depends on whom; folders are incidental |
| The controller holds the business logic | The controller translates; logic belongs in a use case or the domain |
| Laravel's model is the M of MVC | Eloquent is an Active Record; the M is the domain, which may include it |
| Web MVC is the same as Smalltalk MVC | In the original, views observe the model; on the web, each request re-reads |
| MVP, MVVM and MVC are unrelated | They share Separated Presentation and differ in who updates the view |
| A ViewModel is a DTO | A view model has UI state and behaviour; a DTO is a data shape |
| Returning the model as JSON is fine | It couples the contract to the schema and can leak fields |
| Redux is MVC for the front end | Flux and Redux replace MVC with one-way flow |
| Livewire and HTMX are the same | Livewire is a PHP component model with server state; HTMX swaps HTML fragments from any backend |
| Validation in the browser is enough | Anyone can bypass it; validate at the boundary and in the domain |
| 200 with an error body is fine | Clients and caches read the status code first |
| HATEOAS is mandatory in REST APIs | Fielding lists it as a constraint; most APIs stop at level 2 and that is a trade-off |
| Escaping makes validation unnecessary, or the reverse | You need both: validation for correctness, encoding for safety |
| Micro-frontends are always better for big UIs | They add duplication and coordination; use them for team independence, not for fashion |
Cheat sheet
| Topic | Remember |
|---|---|
| Core idea | Separated Presentation: domain never knows the UI |
| Original MVC | Model knowledge, View presents, Controller links input (Reenskaug 1979) |
| Web MVC | Front controller, router, thin controller action, view |
| MVP | Presenter drives a passive view; best for testing UI logic |
| MVVM | View binds to ViewModel; needs a binding engine |
| Presentation Model | Screen state and behaviour in a plain class |
| Unidirectional flow | Action, reducer, state, view; replayable |
| Server-driven | Livewire, HTMX, Inertia; pick by who owns state |
| Input | Form Request or decode step; validated(), never all(); domain rules in the use case |
| Output | View model for HTML, resource or DTO for JSON; version the contract |
| Controller size | Parse, call, respond; extract actions and events |
| Escaping | Default-escaped output; contextual in Go; opt-outs are review flags |
| State | URL first, session for identity and flash, PRG after writes |
| Placement | Interface adapters ring; presenter implements the output port |
| Scale | BFF per experience; micro-frontends for team independence |
| Testing | Unit-test rules, HTTP-test translations, contract-test JSON |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your template calls Order::where('status','new')->count() for a badge. What is wrong, and what is the fix? Must-know
Answer
Answer: The view queries the data layer, so it depends on the schema and can run queries per render. Build the number in the controller or a view composer and pass it as view model data. See View models.
2 — What is the difference between MVC in Smalltalk and MVC in Laravel? Good to know
Answer
Answer: In Smalltalk, the controller handles input events for a running widget and views observe the model. In Laravel, a controller handles one HTTP request, and nothing observes the model; the next request re-reads data. See MVC as originally meant and Web MVC.
3 — When would you choose Passive View over Supervising Controller? Good to know
Answer
Answer: When you want maximum testability and are willing to write more presenter code, for instance when the view toolkit is hard to automate. Supervising Controller uses declarative binding for simple fields to reduce code. See MVP.
4 — Why is json.Marshal(domainOrder) a risky API response? Must-know
Answer
Answer: It couples the contract to the domain type: renamed or added fields change the wire format and may expose internal data. Use a DTO. See Resources and DTOs.
5 — A form submission fails validation. Which status code and which UI behaviour do you use for HTML and for JSON? Must-know
Answer
Answer: HTML: re-render the form with the user's input and field errors, status 422 (or a redirect back with old() input in Laravel). JSON: 422 with an errors object keyed by field. See HTTP details.
6 — Why redirect after a successful POST? Must-know
Answer
Answer: Post/Redirect/Get: a refresh then repeats a GET, not the POST, so no duplicate order is created, and flash messages work. See State in UI interaction.
7 — What does unidirectional data flow give you that two-way binding does not? Important
Answer
Answer: Predictability: only actions change state, in order, through a pure reducer, so state can be logged, replayed and tested. Two-way binding can cascade updates. See Unidirectional data flow.
8 — How do Livewire, HTMX and Inertia differ in where state lives? Important
Answer
Answer: Livewire keeps component state on the server and round-trips it; HTMX keeps state on the server and swaps HTML fragments; Inertia keeps page state in a JavaScript component with props from the server. See Server-driven UIs.
9 — Where do controllers, presenters and views sit in Clean Architecture, and which way do dependencies point? Important
Answer
Answer: In the interface-adapters ring; dependencies point inward to the use cases. The presenter implements an output port the use case declares. See Where MVC sits.
10 — A mobile app and a web UI need different shapes of the same data. What pattern helps, and what does it cost? Important
Answer
Answer: A Backend for Frontend per experience. It tailors payloads and lets the UI team own the API, at the cost of more services and duplicated composition logic. See Microservices: UI composition.
11 — Which tests would you write first for a new screen? Must-know
Answer
Answer: A unit test of the use case's rules, one HTTP test per presentation (status, redirect, rendered or JSON body), a test that user content is escaped, and a contract test for any JSON consumed by other teams. See Testing.
Glossary
| Term | Meaning |
|---|---|
| Separated Presentation | Domain objects work without reference to the UI; any UI depends on the domain, not the reverse |
| Observer Synchronization | Views observe the model so several widgets update without talking to each other |
| MVC | Model-View-Controller: knowledge, its presentation, and the link from user input |
| Controller (original) | Handler of user input for a widget that sends messages to model or views |
| Controller (web) | Request handler that maps HTTP to a use case and a response |
| Model 2 | Web arrangement: controller selects behaviour, model works, view renders |
| Front Controller | One handler for all requests that runs shared behaviour then dispatches |
| Page Controller | One controller per page or action |
| MVP | Model-View-Presenter: the view is thin, the presenter holds UI logic |
| Passive View | MVP variant where the presenter sets every widget and view and model never meet |
| Supervising Controller | MVP variant using declarative binding for simple parts and a controller for complex ones |
| MVVM | Model-View-ViewModel: view binds to view model properties and commands |
| Presentation Model | A class holding the state and behaviour of a screen independent of its widgets |
| Data binding | A mechanism that keeps view properties and view model properties in sync |
INotifyPropertyChanged | .NET interface a view model implements to announce property changes |
ICommand | .NET interface for a bindable command with Execute and CanExecute |
| View model (web) | Display-ready data for one template |
| View composer | Laravel callback run when a view renders, used to attach shared data |
| DTO | Data transfer object: a plain shape for crossing a boundary |
| API Resource | Laravel class (JsonResource) that turns a model into a stable JSON shape |
| Resource collection | Laravel wrapper for lists and paginators with links and meta |
| Form Request | Laravel class combining authorisation, validation rules and validated data |
| Command / Query | An instruction that changes state / a question that does not |
| Presenter (Clean Architecture) | Adapter that implements the use case's output port and shapes a response |
| Output port | Interface in the inner ring through which a use case reports results |
| Interface adapters | Clean Architecture ring that holds controllers, presenters, views, gateways |
| Driving / driven adapter | Hexagonal terms for the side that calls the core / the side the core calls |
| Single-action controller | Laravel controller with one __invoke method |
| Fat controller | Controller that validates, applies rules, accesses data and formats output |
| Flux | Facebook's unidirectional architecture with dispatcher, stores and views |
| Redux | Single store, actions, pure reducers; inspired by the Elm Architecture |
| Reducer | Pure function from previous state and action to next state |
| Elm Architecture | Model, View, Update pattern from the Elm language |
| HTMX | Library that adds HTML attributes for requests and fragment swaps |
| HDA | Hypermedia-driven application: HTML over the wire plus declarative interaction |
| Livewire | Laravel full-stack component framework with server-held state |
| Inertia | Adapter that renders JavaScript page components from server controllers |
| HATEOAS | Hypermedia as the engine of application state: responses carry the next links |
| BFF | Backend for Frontend: one server-side backend per user experience |
| Micro-frontends | Splitting a front end into independently deployed pieces owned by different teams |
| Post/Redirect/Get | Answer a POST with a redirect so refresh repeats a GET |
| CSRF | Cross-site request forgery: a forged request that rides on a user's session |
| XSS | Cross-site scripting: untrusted data run as code in the browser |
| Contextual escaping | Choosing the encoder by where the value lands (HTML, attribute, URL, JS) |
| Snapshot test | Test that compares output to a stored copy |
| Contract test | Test that pins the response shape clients depend on |
httptest | Go package for testing handlers with recorded requests and responses |
References
- Trygve Reenskaug, "MVC: Xerox PARC 1978-79" page, with the May 1979 and December 1979 notes. folk.universitetetioslo.no archive copy; the December 1979 note "Models - Views - Controllers" PDF, archived
- Martin Fowler, "GUI Architectures", 18 July 2006. martinfowler.com/eaaDev/uiArchs.html
- Martin Fowler, Passive View, Supervising Controller, Presentation Model (draft pages, as marked by the author), Page Controller, Front Controller, Richardson Maturity Model, Micro Frontends
- Microsoft, Model-View-ViewModel (.NET MAUI)
- Facebook, Flux In-Depth Overview (archived project); Redux, Three Principles and Essentials: Overview and Concepts; The Elm Architecture
- Carson Gross, Hypermedia-Driven Applications, 2022; htmx, HATEOAS
- Inertia.js, How it works (v2); Livewire, Quickstart
- Robert C. Martin, The Clean Architecture, 13 August 2012
- Sam Newman, Backends For Frontends
- Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, chapter 5, 2000
- OWASP, Cross Site Scripting Prevention Cheat Sheet
- Go: net/http, html/template, encoding/json
- Laravel 13: Routing, Controllers, Validation: Form Requests, Views, Blade, Eloquent: API Resources, HTTP Tests, Starter Kits
- Not read (marked in the text as secondary): the original Sun Model 1 / Model 2 JSP documents and John Gossman's 2005 MVVM post