Skip to content

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 forGo to
The whole topic in a few tablesEverything in one minute
Why presentation must be separateWhy it exists
Reenskaug 1979, Smalltalk, Fowler's GUI Architectures, Model 2Where it comes from
MVC, MVP, MVVM, Presentation Model, Model 2, front controllerThe concepts, one by one
Unidirectional flow, Livewire, HTMX, InertiaData flow and server-driven UIs
JSON resources, DTOs, view models, HATEOASAPI-first presentation
Form requests, validation, commands, presenters, serializersInput and output
Fat vs thin controllers, actions, use casesThin controllers
Escaping, XSS, sessions, UI stateMechanics
The same screen in Go and in LaravelGo, Laravel
Classic problems (fat controller, leaking models, N+1 in views, double submit)Solving the classic problems
Which pattern for which UIChoosing
Clean/Hexagonal placement, BFF, micro-frontends, scalingIn architecture
A hands-on build with testsLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts section.

TermIn plain wordsTiny exampleWhat goes wrong without it
Separated PresentationDomain code never knows how it is shownOrder has no HTML in itEvery new screen copies rules
ModelThe domain data and rules (or the data a screen needs)Order, CreateOrderRules end up in templates
ViewTurns data into pixels, HTML or JSONBlade file, Go templateFormatting scattered in controllers
ControllerTurns user input into calls on the modelPOST /orders handlerHandlers grow into 300-line scripts
Presenter (MVP)Drives a passive view; holds all UI decisionspresenter.OnSubmitUI logic cannot be unit-tested
ViewModel (MVVM)UI state and commands the view binds toOrdersViewModelCode-behind full of widget calls
Presentation ModelThe same idea as ViewModel, older nameFowler 2004Widget APIs hold the state
Front controllerOne entry point for every requestLaravel's router kernel, Go's ServeMuxAuth and logging copied per page
Unidirectional data flowState changes only through actionsRedux, Elm, FluxCascading updates nobody can predict
Server-driven UIServer renders HTML, browser swaps it inLivewire, HTMXDuplicate state client and server
DTO / ResourceWire representation of a modelOrderResourceColumn rename breaks the mobile app
View model (web)Display-ready data for one screenOrderRow with Total: "12.50"Templates full of formatting logic
Form RequestValidation and authorisation at the boundaryStoreOrderRequestInvalid data reaches the domain
Presenter (Clean Arch)Implements the use case's output portJSON or HTML presenterUse case imports a template engine
BFFOne backend per user experiencemobile-bff, web-bffOne API fits no client

The patterns in one table.

PatternWho handles inputWho updates the screenWhere UI state livesTypical home
Forms and ControlsWidget event handlersThe handler, by handIn the widgetsVB, Delphi, small admin tools
MVC (Smalltalk)ControllerView observes ModelModelSmalltalk-80
MVC (web, Model 2)Controller actionTemplate render per requestSession, databaseLaravel, Rails, Spring MVC, Go handlers
MVP (Passive View)PresenterPresenter calls view settersPresenterAndroid classic, WinForms
MVP (Supervising Controller)PresenterBinding for simple parts, presenter for complexModel plus presenterWinForms with binding
MVVM / Presentation ModelView binds to ViewModelBinding engineViewModelWPF, .NET MAUI, Vue, Knockout
Flux / Redux / ElmDispatch of actionsView re-renders from stateOne storeReact apps, Elm
Server-driven (HTMX, Livewire)HTTP event to serverServer returns HTML fragmentServer (session, component)Laravel Livewire, HTMX

Where each piece lives in your tools.

LayerGoLaravel 13
Entry pointhttp.ServeMux, middleware chainroutes/web.php, routes/api.php, middleware
Input validationDecode and check in the handler or a Decode helperFormRequest with rules()
Controllerfunc(w, r) handlerController class, single-action __invoke
Use caseA Service methodAn action class such as CreateOrder
View modelA struct built by the handlerA readonly class or View::composer data
HTML viewhtml/templateBlade
JSON representationDTO struct with json tagsJsonResource, ResourceCollection
SPA bridgePlain JSON APIInertia, Livewire
Testsnet/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 domainSeparated presentation
One file is quick to writeMore files and names to learn
The rule is tested through a browser or HTTPThe rule is tested as a plain function
A second UI copies the ruleA second UI is a new adapter
Layout change can break pricingLayout change touches templates only
Designer and backend developer edit the same fileEach edits their own layer
Easy to see "everything about this page"Must follow one hop between layers
Risk: fat controller, logic in templatesRisk: needless layers for a three-field form
ModelViewControllerModelViewPresenterModelViewViewModelMVC (Smalltalk)MVP (Passive View)MVVMView reads Model (observer);Controller turns input into Model callsView is a dumb interface;Presenter reads Model and pushes to ViewView binds to ViewModel state;ViewModel never references a View type

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 ​

  1. "MVC is a folder layout." app/Http/Controllers, app/Models and resources/views is a layout. MVC is a rule about dependencies: the model must not know the view.
  2. "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.
  3. "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.

YearEventWhy it matters
1978-79Reenskaug writes MVC notes at Xerox PARCModel, View, Controller, Editor named
1980sSmalltalk-80 ships its MVC class libraryThe controller becomes the input handler of a widget
1990sForms and Controls (VB, Delphi), MVP at TaligentRapid UIs, and the testing problem
late 1990sServlet/JSP Model 2, Front ControllerWeb MVC is born
2004Fowler: Presentation ModelUI state in its own class
2005MVVM at Microsoft (WPF), secondary sourceBinding replaces the presenter's wiring
2006Fowler: GUI Architectures, Passive View, Supervising ControllerA vocabulary for MVP
mid 2010sFlux, Redux, Elm Architecture (dates not on the pages we read)One-way data flow
2022HTMX 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.

text
     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 HTML

Real 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 livesSecond UI costsTest cost
In the controllerCopy-paste or call a controllerHTTP request needed
In the model (Eloquent saving hook)Works for every caller of the modelDatabase needed
In a use case or actionNew adapter onlyPlain 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.

text
     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 label

Real 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.

ConcernOriginal MVCWeb MVC
Who observes the modelViews, via the observer patternNobody; the next request re-reads
Life of the controllerThe whole sessionOne request
UI stateModel or viewSession, cookie, query string, DB
Model changes the view without inputYesOnly 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.

BrowserHTTP requestRouterfront controllerMiddlewareauth, CSRF, limitsForm Requestparse + validateControllerthin: map and callUse caserules + repoView model / DTOdisplay-ready dataTemplate / JSONBlade, html/templateResponse200/201/303/422 + bodyBrowserrenders / parsesInvalid input stops at Form Request (422); domain errors come back from the use case as typed errorsand the controller maps them to the representation (re-render form, JSON errors, flash message).
text
     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 HTML

Real 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.

FrameworkFront controllerRoutingControllerView
Laravel 13public/index.php and the HTTP kernelroutes/web.php, routes/api.phpClass in app/Http/ControllersBlade
Go net/httphttp.Server with a ServeMuxPatterns like GET /ordersfunc(w http.ResponseWriter, r *http.Request)html/template
Spring MVCDispatcherServlet@RequestMapping@ControllerThymeleaf, JSP
RailsRack plus the routerconfig/routes.rbApplicationController subclassERB
DjangoURL dispatcherurls.pyView function (their "view" is a controller)Template
ASP.NET Core MVCMiddleware pipelineAttribute or conventional routesController classRazor

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."

text
     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 error

Real 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.

VariantWho maps model to widgetTestabilityCost
Passive ViewPresenter, field by fieldHighest: fake viewMore presenter code and view interface methods
Supervising ControllerBinding for simple fields; presenter for complex casesHigh, but binding is untestedTwo mechanisms to learn
Forms and Controls (for contrast)Event handlers in the formLow: widgets in every testLeast 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.

text
     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-renders

Real 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)VueLivewire
View modelClass implementing INotifyPropertyChangedComponent state (ref, reactive)Livewire component class
Change notificationPropertyChanged eventReactivity systemRequest/response diff
CommandICommandMethod handlerPublic method called from wire:click
Two-way binding{Binding Mode=TwoWay}v-modelwire:model
Where it runsClientClientServer

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.

text
     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.

PatternWho owns UI stateSync mechanism
Presentation ModelPresentation modelManual sync or observer
MVVMView modelDeclarative data binding
Passive ViewPresenterPresenter 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).

text
     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.total

Real 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.

TechniqueLaravelGo
Per-screen data classOrderRowViewModel (readonly)OrdersPage, OrderRow structs
Shared data for many viewsView::composer('layout', ...) or View::shareA function that returns common fields, embedded in each page struct
Display helpersBlade 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.

ViewActionReducerStateViewuser event creates the next action; nothing writes to State directlyClickHTTP requesthx-post, Livewire callServer rendersuse case + templateHTML fragmentswapped into the pageFlux / Redux / Elm: state lives in the client store, the reducer is a pure function(State, Action) to State, views only render. Replay the actions to reproduce any bug.Server-driven (HTMX, Livewire): the state lives on the server; the browser sends events and receives HTML.
text
     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: table

Real 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.

AspectTwo-way binding (MVVM)Unidirectional flow
Change pathAny property may be written from anywhereOnly via dispatched actions
PredictabilityCascades possibleOrder of actions fully determines state
DebuggingInspect live objectsLog or replay actions
BoilerplateLowHigher (actions, reducers)
FitsForms, small screensLarge 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.

text
     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-7

Real 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).

ToolState livesServer outputView languageNeeds a JS framework
Blade (plain)Server, per requestHTML pageBladeNo
HTMXServerHTML fragmentsAny template engineNo
LivewireServer (component state, round-tripped)HTML diffsBladeNo (Alpine.js for small client-side behaviour)
InertiaClient page, props from serverJSON props, page component nameVue, React, SvelteYes
SPA plus JSON APIClientJSONAnyYes

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.

text
     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 rows

Real 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.

SideController taskReturn valueTypical status
CommandValidate, map, call, redirect or return 201Identifier or nothing201, 303, 422
QueryParse filters and paging, call, renderData for the view200, 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.

QuestionIf yesThen
Is most state a function of the database and the user's session?YesServer owns state: Blade, HTMX, Livewire
Is there complex client-only state (drag and drop, offline, optimistic updates)?YesClient store: Redux Toolkit, Pinia, Elm-style
Do you need one backend for a web client, a mobile app and partners?YesAPI-first with resources and versioning
Is your team mostly backend developers who must ship fast?YesServer-driven first; add JS islands where needed
Do you need SEO and fast first paint without a build pipeline?YesServer-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.

text
     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.

PracticeWhyLaravelGo
Explicit field listNo accidental exposuretoArray() of the resourceDTO struct, not the domain type
Stable namesContract with clientsResource keys, not column namesjson:"total_cents" tags
Envelope (data, meta, links)Room for paging and errorsWrapped by default under dataA {"data": ...} map or struct
Empty list is []Clients crash on nullCollections serialise as []Initialise slice with make, not nil
Time in UTC ISO 8601UnambiguoustoIso8601String()time.Time encodes RFC 3339
Money in minor unitsNo float errorstotal_cents integerint64 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.

text
     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 shape

Real 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.

StrategyProsCons
URL version (/v1/)Visible, cache- and log-friendlyDuplicates routes
Header versionClean URLsHidden, harder to test by hand
Additive changes onlyNo version neededCannot remove or rename
HATEOAS linksServer controls available actionsMore 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.

text
     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 -> 422

Real 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).

CheckWhereLaravelGo
Is it valid JSON, are fields of the right typeBoundaryForm Request rules, postJsonjson.Decoder, DisallowUnknownFields
Body sizeBoundaryServer config, middlewarehttp.MaxBytesReader
Is the user allowedBoundary, then domainauthorize(), PolicyMiddleware, explicit check
Is the customer on holdDomainIn the action or a domain serviceIn Service.Create
Unknown or extra fieldsBoundaryvalidated() or safe()->only()DisallowUnknownFields
CSRFMiddlewareVerifyCsrfToken and @csrfA 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.

text
     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 / JSON

Real 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 formContent negotiationLaravelGo
HTML pageAccept: text/htmlview()ExecuteTemplate
JSONAccept: application/jsonResource, response()->json()json.NewEncoder(w).Encode
Redirect after POST303 See Otherredirect()->route()http.Redirect(..., 303)
Validation failure422 Unprocessable ContentAutomatic for JSON requestsExplicit WriteHeader(422)
File downloadContent-Dispositionresponse()->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.

text
     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.

SymptomLikely causeMove
Action longer than about 20 linesBusiness logic insideExtract an action or service
Controller imports a mailer, a PDF librarySide effects in the HTTP layerEvent plus listener or job
Same logic in web and API controllersMissing use caseExtract, call from both
Many unrelated methods in one controllerSeveral resources in one classSplit per resource; single-action for odd ones
Controller test needs the database for a ruleRule in the wrong placeUnit-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.

text
     Customer name stored          Template                       Browser sees
1    <script>steal()</script>      Blade double-curly / Go {{.}}   &lt;script&gt;... 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 #ZgotmplZ

Real 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.

EngineDefaultHow to opt outContextual
BladeEscapes with htmlspecialcharsUnescaped echo syntax, HtmlStringHTML only; use Js::from for JavaScript data
Go html/templateEscapes by contextTyped values like template.HTMLYes: HTML, attribute, URL, JS, CSS
Go text/templateNo escapingn/aNo: never use for HTML
Jinja2, TwigDepends on configurationsafe filter or rawTwig: configurable per strategy
React, VueEscaped by defaultdangerouslySetInnerHTML, v-htmlHTML 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.

text
     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 livesSurvives refreshShareableScales across serversLaravelGo
URL queryYesYesYes$request->query()r.URL.Query()
CookieYesNoYesCookie::queue, encryptedhttp.SetCookie
Server sessionYesNoOnly with a shared storesession(), old(), flashA session library (stdlib has none)
Client storeNo (unless persisted)NoYesInertia shared props, Pinian/a
Component statePer request round tripNoNeeds sticky or shared stateLivewire propertiesn/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.

text
     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"}
CodeMeaningUse in presentation
200 OKSuccess with bodyList and show
201 CreatedNew resourceAPI create, with Location
204 No ContentSuccess, no bodyAPI delete
302 Found / 303 See OtherRedirect (303 forces GET)Post/Redirect/Get
400 Bad RequestMalformed requestUnparseable JSON
401 UnauthorizedNot authenticatedAPI without token
403 ForbiddenAuthenticated, not allowedPolicy denied
404 Not FoundMissing resourceRoute model binding failure
419 (Laravel)CSRF token mismatch or expired sessionForm submitted after session expiry
422 Unprocessable ContentValid syntax, failed validationForm and API validation errors
429 Too Many RequestsRate limitedThrottle middleware
500 / 503Server failure / unavailableGeneric 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.

sql
-- 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.

ApproachQueries for 15 rows with a customer nameLaravelGo
Lazy access in the view1 + 15Default relation accessQuery inside the template function
Eager loading2Order::with('customer')One IN query, map in memory
Join into a read model1Query builder join, DTOJOIN 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.

go
// 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, &cents, &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:

go
// 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:

go
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):

go
// 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:

go
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):

html
<!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:

go
// 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; accept context.Context and return typed errors the handler can switch on with errors.As.
  • Parse templates once at start-up (template.ParseFS with go:embed); a broken template should stop the process, not the first request.
  • Use json:"..." DTO structs, not domain types, for the wire; initialise slices with make so empty lists encode as [].
  • Prefer json.Decoder with DisallowUnknownFields and http.MaxBytesReader for request bodies.
  • Middleware is a function that wraps a http.Handler; compose it around Routes().
  • For the second UI shape, a Passive View presenter and a reducer are plain packages:
go
// 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)
}
go
// 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
<?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
<?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
<?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
<?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.');
    }
}
php
{{-- 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
<?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
<?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
<?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
<?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
<?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
<?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
<?php

namespace App\Enums;

enum OrderStatus: string
{
    case New = 'new';
    case Paid = 'paid';

    public function label(): string
    {
        return strtoupper($this->value);
    }
}
php
<?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
<?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 partLaravel featureNotes
Front controllerHTTP kernel, routes/web.php, routes/api.php, middlewareapi.php is enabled with php artisan install:api
Page controllerController class; single-action controllers via __invokeThe docs recommend single-action for "particularly complex" actions
Input boundaryFormRequest: authorize(), rules(), prepareForValidation(), validated(), safe()Use validated(), never all()
Use caseAction class (your own convention)Laravel has no mandated folder
View modelReadonly class, or data from a view composer (View::composer)Composers run each time the view renders
HTML viewBlade; components; @error, old(), @csrfEscaped output by default
JSON viewJsonResource, ResourceCollection, toResource() (and the UseResource attribute)Pagination adds links and meta
SPA bridgeInertia (Inertia::render), starter kitsServer keeps routing and auth
Reactive server UILivewire components (wire:model, wire:click)State round-trips to the server
Testsget, post, postJson, assertOk, assertJsonStructure, assertViewHas, assertInertiaassertInertia 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 ​

ProblemSymptomSolutionCost
Fat controllerAction of 100+ linesForm Request, action class, eventMore files
Leaking model to view or APIColumn rename breaks clients; hidden fields exposedResource or DTOMapping code
N+1 in the viewQuery count grows with rowsEager load, read modelCare at load time
Logic in templates@if ($o->total > 100 && ...)View model booleanOne more class
Double submitTwo orders on double click or refreshPRG, idempotency key, disabled buttonKey storage
Lost user input on errorForm empties after 422Re-render with old inputSlightly more code
Unversioned APIBreaking change hurts old mobile buildVersion prefix, additive changesParallel resources
Duplicate validationRules differ between web and APIOne Form Request or shared rulesShared class
Presenter in the domainUse case imports net/http or a template engineOutput port implemented by the adapterAn interface
Unescaped outputStored XSSDefault escaping, test for itNone

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 ​

text
     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 queries

In 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 ​

text
     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 #1

Disable 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 ​

SituationRecommendationExtra techniqueReason
Content site or admin, small teamServer-rendered MVC (Blade, html/template)HTMX for small interactionsFewest moving parts
Rich interactive admin, backend-heavy teamLivewireAlpine for client detailsOne language, server owns state
Existing Vue or React team, one web clientInertiaResources as propsKeeps Laravel routing and auth
Mobile app plus web plus partnersAPI-first with versioned resourcesOpenAPI contract, contract testsOne contract, many clients
Large client-side state (editor, canvas, offline)SPA with Redux-style storeOptimistic updatesState logic belongs in the client
Desktop or terminal UI in GoPassive View presenter or Elm-style modelFake view in testsTestable without a toolkit
Windows or .NET desktopMVVM with bindingCommands, INotifyPropertyChangedNative support
Different needs per client (mobile vs web)BFF per clientShared downstream servicesTailored payloads
Many teams on one huge front endMicro-frontendsShared design systemIndependent deploys, with a cost
Three-field formOne handler, no extra layersKeep rules in one functionLayers 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.

ControllerHTTP to input dataPresenter / Viewoutput data to HTML, JSONRepository adapterSQL, Eloquent, pgxGatewaysmail, payment, queueApplication coreentities + use cases (Order, CreateOrder)Use caseinput port in, output port outInterface adapters: MVC lives entirely in this ring. Dependencies point inward only.The presenter implements the output port the use case declares, so the core never imports a template or a JSON encoder.

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.

text
     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 styleWhere it runsGood forCosts
API gateway compositionGateway, server sideSimple fan-out, same shape for all clientsOne shape fits no client perfectly
BFF (Backend for Frontend)One server-side backend per user experienceDifferent payloads for web, iOS, partnersMore services to run; one team per BFF
GraphQL gatewayServerClient-chosen fieldsQuery cost, caching
Server-side includes / ESIEdge or serverFragment pagesFragment latency
Micro-frontendsBrowser or edgeMany teams, one pageDuplicate 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."

text
     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?").

ProblemPresentation-level fix
Replica lag after redirectRead 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 fragmentShort TTL, key by version, invalidate on events
Eventually consistent projectionsUI 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 / devicesServer 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× ​

ScaleStructurePresentation practice
1× (one team, one app)Server-rendered MVC, thin controllersForm Request, action, view model; tests per presentation
10× (several teams, one repo)Modular monolith; API for mobileVersioned resources, contract tests, per-module controllers
100× (many teams, many clients)Services plus BFFs; maybe micro-frontendsOne 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.

text
     Test type            Input                          Assertion
1    Unit (use case)      CreateInput{"",0}              ValidationError with both fields
2    HTTP (HTML)          POST /orders customer=<script> page contains &lt;script&gt;, 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 times

Real 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.

WhatGoLaravel
Use caseorder_test.go plain testUnit test of the action with RefreshDatabase
HTML flowhttptest + strings.Containsget()->assertOk()->assertSee()
JSON contractCompare exact JSON stringassertJsonStructure, assertJsonPath
ValidationAssert 422 and field messageassertSessionHasErrors, assertJsonValidationErrors
Inertian/aassertInertia(fn ($page) => $page->component(...)->has(...))
Presenter or view modelFake view, reducer replayPlain 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.

bash
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/web

Step 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.

bash
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 %1

Step 3: prove the XSS defence.

bash
curl -s -d 'customer=<script>alert(1)</script>&total=1' localhost:8080/orders >/dev/null
curl -s localhost:8080/orders | grep -c '&lt;script&gt;'   # 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.

MetricBefore (fat handler/controller)After (layers)
Jobs per controller action51 (translate)
Presentations sharing the rule1 (copy for each new one)3 (HTML, JSON, presenter)
Test of "total must be positive" needsDatabase and HTTPOne plain function call
New output format touches the domainYesNo
XSS on customer nameYesNo (test enforces it)
Files to read for one change1 (big)2 to 3 (small)

Common misconceptions ​

BeliefReality
MVC is a folder structureIt is a rule about who depends on whom; folders are incidental
The controller holds the business logicThe controller translates; logic belongs in a use case or the domain
Laravel's model is the M of MVCEloquent is an Active Record; the M is the domain, which may include it
Web MVC is the same as Smalltalk MVCIn the original, views observe the model; on the web, each request re-reads
MVP, MVVM and MVC are unrelatedThey share Separated Presentation and differ in who updates the view
A ViewModel is a DTOA view model has UI state and behaviour; a DTO is a data shape
Returning the model as JSON is fineIt couples the contract to the schema and can leak fields
Redux is MVC for the front endFlux and Redux replace MVC with one-way flow
Livewire and HTMX are the sameLivewire is a PHP component model with server state; HTMX swaps HTML fragments from any backend
Validation in the browser is enoughAnyone can bypass it; validate at the boundary and in the domain
200 with an error body is fineClients and caches read the status code first
HATEOAS is mandatory in REST APIsFielding lists it as a constraint; most APIs stop at level 2 and that is a trade-off
Escaping makes validation unnecessary, or the reverseYou need both: validation for correctness, encoding for safety
Micro-frontends are always better for big UIsThey add duplication and coordination; use them for team independence, not for fashion

Cheat sheet ​

TopicRemember
Core ideaSeparated Presentation: domain never knows the UI
Original MVCModel knowledge, View presents, Controller links input (Reenskaug 1979)
Web MVCFront controller, router, thin controller action, view
MVPPresenter drives a passive view; best for testing UI logic
MVVMView binds to ViewModel; needs a binding engine
Presentation ModelScreen state and behaviour in a plain class
Unidirectional flowAction, reducer, state, view; replayable
Server-drivenLivewire, HTMX, Inertia; pick by who owns state
InputForm Request or decode step; validated(), never all(); domain rules in the use case
OutputView model for HTML, resource or DTO for JSON; version the contract
Controller sizeParse, call, respond; extract actions and events
EscapingDefault-escaped output; contextual in Go; opt-outs are review flags
StateURL first, session for identity and flash, PRG after writes
PlacementInterface adapters ring; presenter implements the output port
ScaleBFF per experience; micro-frontends for team independence
TestingUnit-test rules, HTTP-test translations, contract-test JSON

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Separated PresentationDomain objects work without reference to the UI; any UI depends on the domain, not the reverse
Observer SynchronizationViews observe the model so several widgets update without talking to each other
MVCModel-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 2Web arrangement: controller selects behaviour, model works, view renders
Front ControllerOne handler for all requests that runs shared behaviour then dispatches
Page ControllerOne controller per page or action
MVPModel-View-Presenter: the view is thin, the presenter holds UI logic
Passive ViewMVP variant where the presenter sets every widget and view and model never meet
Supervising ControllerMVP variant using declarative binding for simple parts and a controller for complex ones
MVVMModel-View-ViewModel: view binds to view model properties and commands
Presentation ModelA class holding the state and behaviour of a screen independent of its widgets
Data bindingA 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 composerLaravel callback run when a view renders, used to attach shared data
DTOData transfer object: a plain shape for crossing a boundary
API ResourceLaravel class (JsonResource) that turns a model into a stable JSON shape
Resource collectionLaravel wrapper for lists and paginators with links and meta
Form RequestLaravel class combining authorisation, validation rules and validated data
Command / QueryAn 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 portInterface in the inner ring through which a use case reports results
Interface adaptersClean Architecture ring that holds controllers, presenters, views, gateways
Driving / driven adapterHexagonal terms for the side that calls the core / the side the core calls
Single-action controllerLaravel controller with one __invoke method
Fat controllerController that validates, applies rules, accesses data and formats output
FluxFacebook's unidirectional architecture with dispatcher, stores and views
ReduxSingle store, actions, pure reducers; inspired by the Elm Architecture
ReducerPure function from previous state and action to next state
Elm ArchitectureModel, View, Update pattern from the Elm language
HTMXLibrary that adds HTML attributes for requests and fragment swaps
HDAHypermedia-driven application: HTML over the wire plus declarative interaction
LivewireLaravel full-stack component framework with server-held state
InertiaAdapter that renders JavaScript page components from server controllers
HATEOASHypermedia as the engine of application state: responses carry the next links
BFFBackend for Frontend: one server-side backend per user experience
Micro-frontendsSplitting a front end into independently deployed pieces owned by different teams
Post/Redirect/GetAnswer a POST with a redirect so refresh repeats a GET
CSRFCross-site request forgery: a forged request that rides on a user's session
XSSCross-site scripting: untrusted data run as code in the browser
Contextual escapingChoosing the encoder by where the value lands (HTML, attribute, URL, JS)
Snapshot testTest that compares output to a stored copy
Contract testTest that pins the response shape clients depend on
httptestGo package for testing handlers with recorded requests and responses

References ​

Built by Morteza Negahi