The scenario below describes a typical client/server/database infrastructure with Flash as the client, PHP/Apache as the server and a Mysql back-end as the database, probably the most typical setup. The example is, a user just purchased a decoration in their virtual store. Several things need to be done:
1. The client (Flash) needs to visually place the item where the user purchased it.
2. The client needs to visually deduct the money spent.
3. The client needs to tell the server (PHP) about the purchase.
4. The server needs to validate that it is a real item.
5. The server needs to validate that the user has enough money.
6. Finally, the server needs to save it in the database for when the user returns next time.
Steps 1-3 do not concern us, as the Flash development team will handle these processes, we care about 4-6. Below is some sample PHP code, that doesn't do real processing, just pretends to:
<?php
if (!doesItemExist($_REQUEST['item_id'])) {
echo 'ERROR';
exit();
}
if (!doesUserHaveEnoughMoney($_REQUEST['item_id'])) {
echo 'ERROR';
exit();
}
echo '1';
flush_buffers();
saveItemForUser($_REQUEST['item_id']);
function flush_buffers(){
ob_end_flush();
ob_flush();
flush();
ob_start();
}
In the above code, we do our basic error checking first, if there is an error we return it right away and the client will display an error to the user. This should never get triggered unless the client and server are out of sync.
If there are no errors, we immediately return 1 to the client so the user can keep playing. We then do our actual processing of saving the information to the database. In other scenarios, if there is no error checking required, we can just return "1" right away and keep processing.
Don't quite understand what this script is doing? Run this sample script to see:
<?php
echo 'Processing...<br/>';
$y = 0;
for ($x = 0; $x < 500; $x++) {
$y++;
}
echo 'Done processing, lets respond<br/>';
echo 'The rest we can do silently....<br/>';
flush_buffers();
for ($x = 0; $x < 50000000; $x++) {
$y++;
}
echo 'Now we are finally done<br/>';
function flush_buffers(){
ob_end_flush();
ob_flush();
flush();
ob_start();
}
What you should see are the first 3 echo statements appear almost immediately, then the page will keep running until our extremely long for loop is done. Once this is done, then the final message will display. Enjoy!
Published on Jan 10, 2011
Tags: Optimization
| client/server
| speed
| Theory