Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel API controller structure?

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  
like image 933
Azrul Rahim Avatar asked Nov 25 '13 00:11

Azrul Rahim


1 Answers

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.

like image 117
Manuel Pedrera Avatar answered Sep 23 '22 14:09

Manuel Pedrera