3

I'm writing a rich JS application, I'd like broad advice as to how to structure the JS/PHP. I'm not sure how to split up this question, sorry if it's asking too many things. I'm suffering from information overload!

I expect the JS will requests JSON objects from a single PHP file. I'd like a minimal but effective pattern for PHP to respond to requests that is concise and effective. Perhaps the JS would invoke model-like objects which query a database and return JSON to the client.

What would be a good pattern for the PHP side? I've hacked together a PHP file which messily has a large switch statement parsing for instructions from the client, with associated data. A single request could contain multiple instructions. For example, javascript sends a request:

$.ajax({
    url: '/ajax.php', dataType: 'json',
    data: {instructions: [{
        instruction: "newPerson",
        data: {
             name: person.name,
             email: person.email
             city: person.city
        }
    }]},
    success: callback, error: ajaxFail
});

The callback would be a global handler dealing with any objects the PHP returns, from this request or others. For example, the above might receive a new person object with the person ID generated by PHP inserting into the DB, as well as a city object also with its ID. Other requests might also return those objects, so a single handler makes sense? (One question would be how the javascript associates the returned objects with the insertion submitted)

I'm ashamed by my PHP page code, but it looks something like this:

$return = array();
$instructions = $_REQUEST['instructions'];
foreach ($instructions as $instruction){
    switch($instruction['instruction']){
        case 'findPoeple':
            $data = $instruction['data'];
            $res = DB::query("select player from person where player like '%". DB::esc($str) ."%'");
            $return['players'] = array();
            while ($row = DB::fetch($res)){
                $return['players'][] = $row['player'];
            }
        break;
        case 'loadAllPeople':
            // similar code
        break;
        case 'newPerson':
            // similar code
        break;
        default:
            die("command '$command' not recognised");
        break;
    }
}
echo json_encode($return);

Clearly there's too much wrong with this to say what to change! But I've made fairly clear what the end result I'm looking for is. Can anyone point me to concise patterns specifically demonstrating this kind of approach for JS/PHP that uses OOP to implement this in a respectable way?

MVC made sense to me until rich JS apps became possible, the boundaries seem very blurred, any enlightenment would be a god send, I'm starting from scratch here now.

Thank you!

1
  • 1
    start with a dispatcher rather than using the switch Commented Oct 18, 2012 at 3:03

1 Answer 1

5

tl;dr: A minimal but effective pattern for PHP to respond to requests that is concise and effective is to use a separate PHP script for each type of request

Instead of trying to route requests in PHP, it's probably simpler, easier and more performant to just let the web server handle routing automatically. All you'd have to do is separate each case in your switch block into its own script, like this:

/findpeople.php
/loadallpeople.php
/newperson.php

That way, when you receive a request for 'newperson.php' you know, explicitly, what parameters are required(1), how to validate each parameter(2) and what kind of resource the client is expecting back(3).

For example:

  1. 'newperson.php' might require a name, email and city to create a new person
  2. A name is probably a string (from 3 to 16 characters or some other arbitrary range); an email address is basically a string but has some finnicky stuff when it comes to validating correctly and a city is probably a string with similar constraints as a name
  3. If the client is attempting to create a new person, they might want to know if the request was successful or not, and the new person's identifying feature (a person_id value from your database, maybe?)

Finally, if you want to group multiple requests in Javascript the simplest approach is probably just to execute multiple separate AJAX requests, one for each instruction.


If you want to take it to the next level, do a bit of research into REST-ful web services and then rethink how you are exposing resources (in this case your collection of person objects). A (more) REST-ful architecture around person objects might look like this, instead:

POST /person/ - creates a new person
POST /person/person_id - modifies a person
GET /person/person_id - retrieves info about an individual
GET /person/ - retrieves all people

You can access the HTTP request method in PHP via the $_SERVER['request_method'] variable and then act accordingly.

Some basic info on REST principles and implementation:

  • How I Explained REST To My Wife
  • (Sorry, I would have provided links to Wikipedia and to Roy Fielding's dissertation, in which he 'invents' REST, but don't have the reputation required)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.