jnortey
jnortey

Reputation: 1625

Best approach for handling multiple PHP scripts as a backend REST service?

I have a typical website setup where I'm using AJAX to communicate with PHP scripts which are then reading and writing data to a MySQL database. In my previous projects, the amount PHP scripts I needed to make were small since there weren't many variations in the data that I needed to read or write. This site is a bit different, and my normal approach of creating a different PHP script for each AJAX call has resulted in a large amount of PHP scripts.

I decided to take a different approach and group similar queries in the same PHP script. For example, if I have the following calls:

getGroupById
getAllGroups
createNewGroup

In my previous approach, I would have three separate php files, but now I have one that does all three of these.

The second approach I have taken is proving to be unmaintainable as the project is grows. For example, if I want to have multiple GET calls in the same script, I'd have to now pass in another parameter to the script from the AJAX call so that the PHP script knows which query to perform.

Which of these two approaches would be better? Are there any well known practices or design patterns for handling this?

Upvotes: 0

Views: 2019

Answers (1)

samvv
samvv

Reputation: 2134

If you really want to be RESTful, try to make your PHP file structure independent of the way you want your AJAX requests to be.

One common design pattern is to make a representation for each separate entity of data you have and then define the CRUD-operations on that representation. The HTTP method header then serves as the identifier of which operation should be performed.

For example, lets say you have the following "pieces" of data:

  • user: a member of your website
  • group: a group of members

If possible, use something like Apache's mod_rewrite in a .htaccess to create some nice looking URLs like this:

Next, pass your parameters in a GET, PUT, DELETE or POST request using AJAX to one of these URLs. Usually the AJAX library allows you define operations other than GET or POST. For example to delete user named Bob with ID 415 in jQuery you could write something like:

$.ajax ({
  url: 'http://example.com/api/user'
  method: 'DELETE',
  data: { id: 415 }
  success: {
    // it works!
  }
});

Next thing is to catch the data with PHP. I'd suggest creating a separate file for each "piece" of data but you can change this when your scripts are getting bigger. It's just a matter of adjusting the rewrite rules of your HTTP server.

api/user.php

// determine what operation was requested
switch ($_SERVER['REQUEST_METHOD'])
{
  case 'POST':
    $data = $_POST;
    // ...
  case 'GET':
    $data = $_GET;
    // e.g. if an ID was provided, fetch one user, else fetch all of the users
    if (isset ($data ['id']))
      fetch_user ($id);
    else
      fetch_users ();
    break;
  case 'PUT':
    $data = parse_str (file_get_contents('php://input'), $put_vars); // see below
    // ...
  case 'DELETE':
    $data = parse_str (file_get_contents('php://input'), $put_vars); // see below
    // ...
  default:
   // 405 = Method Not Allowed
   http_response_code(405); // for PHP >= 5.4.0
   exit;
}

// a whole list of functions to add, retrieve, delete and manipulate users

function fetch_user ($id)
{
  $query = "SELECT * FROM users WHERE id = ...";
  // ...
}

function fetch_users ()
{
  // ...
}

Sources:

Upvotes: 1

Related Questions