7

Which one this controller structure for user api make sense

Separate controller for UI and API for every api version

/app/controllers/UsersController.php
/app/controllers/api/v1/ApiUsersController.php

or

Separate controller for UI and API and handle versioning in code

/app/controllers/UsersController.php
/app/controllers/api/ApiUsersController.php 

or

Use single controller, detect /api/ call within router. Return html/json depending on the url.

/app/controllers/UsersController.php  
Manuel Pedrera
  • 5,347
  • 2
  • 30
  • 47
  • The first option is clear and direct. The last one would eventually be confusing if you open your API to the public. – Hass Nov 25 '13 at 01:31

2 Answers2

7

Definitely the first option is the best out of the three, and the reasons are scalability and maintenance.

If you use only one controller, as proposed in the third method, you will end up soon with a messy class with thousands of lines. Not only this is not going to scale well, but it will be hard to work with for you and your teammates.

The second choice is better than the third one, but still not the best. It's a better practice to be supporting API versioning from the start, and it will keep your routes, files and namespaces more organized.

By the way, instead of naming it ApiUserController you can use UserController too, as long as you are namespacing properly. So, you could have \UserController and Api\V1\UserController existing together.

Manuel Pedrera
  • 5,347
  • 2
  • 30
  • 47
  • Manuel, can you please explain why to use different controllers if all the difference would be either to output JSON or HTML. As for me having the same controller with only different return statements is a DRY violation. I must be not taking something into consideration. Do you mean that sooner or later the Web/API corresponding methods would become more heavy then just it seems to me know? – AHeavyObject Apr 26 '17 at 23:16
  • I would imagine, it is just because if you have one method for example index in your API controller that returns json, but you want a web controller with index to return a vew then it won't get messy trying to have logic to seperate the requests to requiring json and can just have clearly seperated controllers to handle each things. Keeps your code contained. – James mcconnon Jun 08 '20 at 12:41
1

Personal opinion. I prefer 1st option. All in 1 app, and versioning via namespace.