Author Topic: AJAX + JSON = MVC?  (Read 1960 times)

Offline codestryke

  • Administrator
  • Level 33
  • *****
  • Posts: 588
  • Reputation: +22/-0
    • View Profile
    • eXtremeCast Games
AJAX + JSON = MVC?
« on: February 22, 2009, 05:17:28 PM »
First this article assumes you already know about the HTTP.Request method. If you know know what that is they I suggest a Google search there are numerous articles on the web about HTTP.Request.

Quote from: Wikipedia
Though MVC comes in different flavors, control flow is generally as follows:

   1. The user interacts with the user interface in some way (for example, presses a mouse button).
   2. The controller handles the input event from the user interface, often via a registered handler or callback.
   3. The controller notifies the model of the user action, possibly resulting in a change in the model's state. (for example, the controller updates the user's shopping cart).[4]
   4. A view uses the model indirectly to generate an appropriate user interface (for example, the view lists the shopping cart's contents). The view gets its own data from the model. The model and controller have no direct knowledge of the view.
   5. The user interface waits for further user interactions, which restarts the cycle.

This was the model we used for our latest creation CyberStryke (CS). I originally started with using XML as the communications layer from the PHP scripts to the JavaScript on the client. The problems with using XML for our purposes was a) wordy, I mean it's nice to be human readable but when it comes to transfer rate it just repeates to many things b) Parsing XML via JavaScrip was like pulling teeth, to me it was very unfriendly transversing though nodes using firstNode, nextNode etc.

I didn't let that stop me though the original in house builds used XML until I came across an article about JSON. At first glance JSON looked a lot less wordy. So I started hacking some example codes to see how it would interact with the JavaScript. It was then I saw the true power of JSON. The ability of not only passing back array information which was easier to iterate though then XML but then you have the option to eval the JSON! This is when all the pieces came together and I started to recode the entire game to use JSON.

The browser for CyberStryke is our viewer. The viewer is only there for display purposes. It knows how to receive input and send it to controller and then display the result passed back. With this approach the viewer can be the browser, we could code it in Java, a stand alone application or even a Flash applet.

When you press the up arrow key, the viewer sends a request to the controller telling the system we want to go up. The controller is our php backend. It then hands off the request to one of the models, in this case our movement routines. The model does the checking to see if we can move and if so hands back to the controller a function call with a JSON array as the parameter for the function. Did you catch that little bit there? The PHP is sending back what function to execute on the Javascript! You control what to execute and the data you are sending it. So for a normal movement in CyberStryke the viewer (browser sees):

drawMatrix( data );
drawOthers( data );
drawPrograms( data );
drawPlayer( { "location" : "Location: 169.0.7.3" , "unread" : "0", "status" : ""  } );

The data is the JSON data it also passes back, I deleted that part just so it's cleaner. On the last call though drawPlayer we are passing back the new location, how many unread messages the player has and the status. On the browser we have a javascript function that correlates to each of those calls and knows how to display the data given to it. For the drawPlayer it's looks a bit like this:

function drawPlayer( response ) {
  $('location').innerHTML = response.location;
  $('unread').innerHTML = response.unread;

  if( response.status != "" )
    showStatus(response.status);
}

drawMatrix - draws the matrix or the corp
drawOthers - draws other players on the matrix that you can see
drawPrograms - clears your program list and then repopulates it with the data

This MVC model of developement to me has made coding javascript much easier as I'm more concerned about the specific action of drawing or updating what the user is seeing and all the logic is then offloaded to the backend. Probably the cleanest javascript I've ever written LOL :) Please note I'm using Prototype so $('') is shorthand for document.getElementById('')


Hope this helps some of your or puts you on a new path of development.

Creating online addictions, one game at a time:

Offline Sunchaser

  • Game Owner
  • Level 22
  • *
  • Posts: 274
  • Reputation: +2/-0
  • Game Owner
    • View Profile
    • Medieval Europe
Re: AJAX + JSON = MVC?
« Reply #1 on: February 23, 2009, 04:41:39 AM »
Excellent article CodeStryke.

I didn't understood the part where the model sends back to the controller

Quote
and if so hands back to the controller a function call with a JSON array as the parameter for the function.


1) a controller class receives for example /users/move/right (i am using the cakephp framework)
2) the controller calls the correct model method (Example: User -> move( user_id, right ) ).
The model makes checks and data is eventually changed on the db

You say move should return functions to be called by javascript? how? the method move returns an array of functions with parameters?







Offline lolninja

  • Level 19
  • *
  • Posts: 194
  • Reputation: +5/-0
  • BSc powered Programmer
    • View Profile
    • HTTPmmo
Re: AJAX + JSON = MVC?
« Reply #2 on: February 23, 2009, 04:57:50 AM »
The easiest way to visualize this from a cakePHP point of view would be, that the controller loads a view which contains the formatting for the client side call back.
So you would write a normal MVC system using cakePHP, then rather than displaying loads of HTML in your rendered views, you just render a block of JSON which is read and processed by the Javascript. In my prototypes the way I've implemented this was to have a controller which handles all of my incoming tragic, and uses the strategy pattern to execute the relevant model server side, this allows you to form links like example.com/message/user/moves/to/x/y, the message controller will then take the uri data and load the user object calling the moves function.
Once the move has completed, the controller will render a block of JSON using a standard view, and the return information is then extracted from the model.

 


SimplePortal 2.3.3 © 2008-2010, SimplePortal