Web app and API in same Laravel project?

2019-05-08 05:21发布

问题:

I am trying to figure out the best way to structure a new project that I am about to embark on.

We currently have a web app and a mobile app which are both fed data by an API. Currently the web app is done on an installation of CodeIgniter and the API is done on a separate installation of CodeIgniter. For data, the web app makes calls to the API and then handles the returned data.

At this point it looks like we are doing to switch into Laravel for the web app and I was thinking that it might be a good opportunity to also redo the API as some of our rules have changed and it might be time to get off CodeIgniter altogether.

Now for the question: I have read a few sources of people building their web app and API into the same Laravel project and just using the routing to control the mapping of the API and the web app separately. While this seems like an interesting idea it makes me wonder if it is the best practice as I would wonder if heavy API traffic would slow down the web app and vice versa.

Question:

Would the best practice be to keep the api decoupled in its own project or would it be OK to do it in the same project?

Follow Up Question

To make a call from the web app through the API if it is not decoupled, would that just be a call to the API route? Better to go through classes?

回答1:

In my opinion you have 2 choices:

  • Build only the API with Laravel (Response::json everywhere), then build the web app using a JS framework like Angular, or jQuery. Both the web app and the mobile app could make AJAX requests to the Laravel app, and the JS framework would handle displaying it. This would be the "not building the api + web app in the same place" solution. You could have your web app built wherever you want, or inside the Laravel app itself.

    The API would be easy to maintain, and you could even merge the web app and the mobile app, since they would both do the same (unless you actually want them to be different). Also, it's easier to extend, since the interface remains the same across any API consumer app.

    This will help a lot: https://laracasts.com/series/incremental-api-development

  • Building the API and the web app in the same place, would require separating your app in 2: one part would respond to AJAX requests and return JSON and the other part would answer the normal way, returning php views and all that..

    This means a lot of extra work and double the amount of views, since you would have to build the views handled by the the mobile app and the views handled by Laravel itself. That's a lot to cover and maintain (and test).

It depends on what kind of project you're building. Is it a SPA?