3

This question is on my mind for some time now.

Let's say I have a PHP website which has an API (SOAP, REST, etc.) and this API serves almost the same things that are available through the pages (e.g. blog post, comments, statistics, etc.).

In order to avoid code redundancy/duplication I'm thinking of using the API even for the site itself because, although most of code factorization is already done by using MVC's Model, some logic is still in double if a site has to offer an API.

Example when a visitor retrieves a given blog's post:

Classic GUI:

  1. HTTP request: sent by browser
  2. PHP Controller: read user input
  3. PHP Model: fetch the post from database
  4. PHP Controller: populate the view
  5. PHP View: render HTML
  6. HTTP response: sent to browser

GUI using API:

  1. HTTP request: sent by browser
  2. PHP "posts" Controller: read user input
  3. HTTP API request: sent by PHP Controller to site's API URL
  4. PHP "api" Controller: read API request
  5. PHP Model: fetch the post from database
  6. PHP "api" Controller: populate the "api" view
  7. PHP "api" View: render (XML, JSON, etc.)
  8. HTTP API response: sent to PHP Controller of point 2.
  9. PHP Controller: populate the view
  10. PHP View: render HTML
  11. HTTP response: sent to browser

My opinion is that GUI should be a layer that consumes API (a new layer) but I am concerned about performances issues because, in PHP websites, an API call goes through an HTTP request which takes time.

CDuv
  • 2,098
  • 3
  • 22
  • 28

1 Answers1

1

Generally, you don't want to have the server make "inner" calls like that to itself. Instead, have the initial HTML include Javascript which drives the interaction:

  1. HTTP request for GUI: sent by browser
  2. HTTP response: static HTML (heavily cached)

  3. HTTP API request: sent via AJAX to site's API URL

  4. PHP "api" Controller: read API request
  5. PHP Model: fetch the post from database
  6. PHP "api" Controller: populate the "api" view as JSON
  7. HTTP API response: sent to browser of point 3.

  8. Javascript: alter the DOM

The "extra" call takes time but RESTful architectures strive to optimize user-perceived performance via caching (often resulting in no network activity at all) just as much as chunking. See a previous answer of mine for more analysis.

Community
  • 1
  • 1
fumanchu
  • 14,419
  • 6
  • 31
  • 36
  • It's sure how things are generally done but this makes JavaScript the API client and would then either makes JS support mandatory or require to code the fallback PHP scripts that does all what the JS+API couple is doing. Maybe that a simpler solution would be have an API that is both usable via SOAP/REST (over HTTP: `.../api/fetchPost/42`) and internal method calls (`Api::getInstance()->fetchPost(42)`? – CDuv Jul 12 '12 at 20:36