Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Web and API controller structure. Separate vs DRY

Tags:

laravel

I want to build a Laravel application which users both web and API parts. The common (and mine as well) question is whether to use separate controllers or not.

There are 2 options:

  1. Separate controllers Laravel API controller structure?

  2. Use one controller and check the request type (is Ajax, or depending on the request link) and return either JSON or HTML. Laravel resource controllers for both API and non-API use

Those who have the 1-st opinion doesn't explain the DRY problem solution - web and API controllers would be the same except the return statement (JSON or HTML view). But since most post recommend to separate controllers I suspect I don't understand something about the DRY problem solution.

I don't see any disadvantage of the second method. But people say something like

If you use only one controller, 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.

Please explain me the DRY problem solution for the first approach (separate controllers) and the possible underwater rocks in the second approach (single controller)

Please explain which approach is preferable.

like image 844
AHeavyObject Avatar asked Apr 26 '17 23:04

AHeavyObject


1 Answers

I think this is a great question, and I too am keen to see the responses.

I can see the arguments for both approaches. I however would create and maintain separate controllers, whilst using services to share common logic between the controllers where it is known that this will never change.

For example, if you allow users to upload avatar images. I would put such logic in a service and consume this service in both controllers.

The reason for this approach in my mind, is that the web and API logic may diverge and it would therefore be easier to iterate each without impacting the other.

If this is unlikely, then I would still create separate routes, but point them both at the same controllers, so that if it did change in the future, you can simply re-point the API routes to their own controllers.

like image 179
fubar Avatar answered Oct 22 '22 13:10

fubar