Question about controllers

In chapter 8, the book says that it’s a good practice to have all interactions with a model in a dedicated controller.

However, once we are in the chapters about templating (14-15), we create several controllers interacting with several models dedicated to control the website.

My questions are :

  • First, does all the controllers we’ve created in the previous chapters (AcronymsController, CategoriesController, UsersController) useless for the interaction with the website ?
  • Secondly, is this the best practice to integrate all the routes related to the website within the same controller ?


@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hi @nidupb

In general yes, controllers for APIs don’t really have much cross-over with front-end controllers - the main problem being one (usually) returns JSON, whereas the other returns HTML.

There’s nothing stopping you splitting out business logic into a separate class/repository/something etc if you’re duplicating a lot of code. But if you are getting to this point you may just want your website to interact with your API rather than directly talking to the DB etc.

And yes, for large websites you should definitely split up your routes into different controllers. So you could have a ShoppingCartController for all the routes to do with a shopping cart, and an AccountController for accounts etc. The idea is to make the code maintainable and avoid monster controller files. Hope that helps!

Thanks for your answer, it helps ! Can you develop a bit this :

I’m not sure to understand what you meant, thanks !

Basically make the website just another client of the API, so the route handlers for the website just call the API - usually which is a different app.

For example, let’s say you have a big application - you have an API for the iOS app and the Android app and then you have a website. At some point you want to change the registration flow for when a user signs up so that it sends a welcome email to the user. If you have one big app with an API for registration and then a website controller for the website registration, the chances are you’re going to have to duplicate the code that sends the email. A better approach is to use the website app to collect all the information that API needs and then send a request to the API. That way, you make the change in the API only and your web code doesn’t even need to change.

Does that help?

Yes, it’s clear, thank you !