0

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?

jnortey
  • 1,625
  • 2
  • 10
  • 17
  • I'd recommend standardizing on a "restful collection" interface / abstract class (even something like `ArrayAccess` would do, for simple cases), plus liberal use of `PATH_INFO`. At that point you can have all your resource URLs follow a standard convention, have one script to do all the navigation/routing, and maybe have one class for each type you expose. – cHao Nov 23 '13 at 23:43

1 Answers1

1

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:

Community
  • 1
  • 1
samvv
  • 1,934
  • 1
  • 18
  • 26
  • I appreciate the thorough information, however your answer highlights a couple things that I'm trying to avoid. Putting all of the CRUD operations in one file has proven to become unmaintainable for me. I also need to validate and sanitize the data that comes in. After doing all of that for all CRUD operations, the single php file begins to get cluttered. Also, the branching in a single CRUD operation begins to become un maintainable as well. Just as you have shown above, I may end up having multiple POST requests in the same php file. – jnortey Nov 24 '13 at 19:49