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  
1
  • The first option is clear and direct. The last one would eventually be confusing if you open your API to the public. Commented Nov 25, 2013 at 1:31

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.