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!