Laravel API controller structure?

2019-04-10 06:16发布

问题:

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:

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.



回答2:

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