WorldController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. //
  3. // Database Mapping Test
  4. //
  5. class WorldController extends AppController {
  6. // Needed to enable JsonView
  7. // http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#enabling-data-views-in-your-application
  8. public $components = array('RequestHandler');
  9. public function index() {
  10. // Read number of queries to run from URL parameter
  11. // http://book.cakephp.org/2.0/en/controllers/request-response.html#accessing-request-parameters
  12. $query_count = $this->request->query('queries');
  13. $should_return_array = True;
  14. if ($query_count == null) {
  15. $query_count = 1;
  16. $should_return_array = False;
  17. }
  18. $query_count = intval($query_count);
  19. if ($query_count == 0) {
  20. $query_count = 1;
  21. } elseif ($query_count > 500) {
  22. $query_count = 500;
  23. }
  24. // Create an array with the response string.
  25. $arr = array();
  26. // For each query, store the result set values in the response array
  27. for ($i = 0; $i < $query_count; $i++) {
  28. // Choose a random row
  29. // http://www.php.net/mt_rand
  30. $id = mt_rand(1, 10000);
  31. // Retrieve a model by ID
  32. // http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find
  33. $world = $this->World->find('first', array('conditions' => array('id' => $id)));
  34. // Cast numbers to int so they don't get quoted in JSON
  35. $result = $world['World'];
  36. $result['id'] = (int) $result['id'];
  37. $result['randomNumber'] = (int) $result['randomNumber'];
  38. // Store result in array.
  39. $arr[] = array("id" => $result['id'], "randomNumber" => $result['randomNumber']);
  40. }
  41. # Return either one object or a json list
  42. if ($should_return_array == False) {
  43. $this->set('worlds', $arr[0]);
  44. } else {
  45. $this->set('worlds', $arr);
  46. }
  47. // Use the CakePHP JSON View
  48. // http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
  49. $this->set('_serialize', 'worlds');
  50. }
  51. }
  52. ?>