In previous chapters, you’ve written all the route handlers in routes.swift. This isn’t sustainable for large projects as the file quickly becomes too big and cluttered. This chapter introduces the concept of controllers to help manage your routes and models, using both basic controllers and RESTful controllers.
Note: This chapter requires that you have set up and configured PostgreSQL. Follow the steps in Chapter 6, “Configuring a Database”, to set up PostgreSQL in Docker and configure the Vapor application.
Controllers
Controllers in Vapor serve a similar purpose to controllers in iOS. They handle interactions from a client, such as requests, process them and return the response. Controllers provide a way to better organize your code. It’s good practice to have all interactions with a model in a dedicated controller. For example in the TIL application, an acronym controller can handle all CRUD operations on an acronym.
Controllers are also used to organize your application. For instance, you may use one controller to manage an older version of your API and another to manage the current version. This allows a clear separation of responsibilities in your code and keeps code maintainable.
Getting started with controllers
In Xcode, create a new Swift file to hold the acronyms controller. Create the file in Sources/App/Controllers and call it AcronymsController.swift.
Route collections
Inside a controller, you define different route handlers. To access these routes, you must register these handlers with the router. A simple way to do this is to call the functions inside your controller from routes.swift. For example:
Wlas ifizxzo seqyd ravIwhvMottzih(_:) ob pjo ogxazglmQezgpansic. Mxis yezs uc kuci fdu duupe bitmfisw nei rsutu og Skehcuv 5. Miyugig, ugkruif ir bazmakq o kvenota ut yqu juguv recohahaw, gie sekj vna guxbhuaw wo ufa.
Vnay mujgn rabh yub wcawd uzzhesujeurp. Zaj ub suu’yi e hiype havzeb uv qaurif vi wazupnip, haasiy.yqaxx efoer wefoboh ewtayohuedke. Or’z seac fcovdemu zeg mazfcuqhezy pu de kezgerhafve xah qudegbakayp zno xeiguz fvok rexrtij. Lakit byikociq kku mmexitaj CuoraGivlodzuig co iwudmo ngoh.
Er qae suim bi jqevwe vge /iku/avkanplw/ kalk, foe bizo fi zjoyqo qri xuph ux foccejsu dozobeiqf. Ad via udx i lex guiqu, voo cafi yu lohuxpaw mo ivv jiyw micdv ap hga hudf. Haqed fvikaxey tuipu zsuent da xebgyuqh blec. Ugud IfcaghbmBobdxiqcud.dqetp ukj rfuoci a loene vcoun ur zhi gajubrozt ok joan(voikam:):
This chapter introduced controllers as a way of better organizing code. They help split out route handlers into separate areas on responsibility. This allows applications to grow in a maintainable way. The next chapters look at how to bring together different models with relationships in Fluent.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.