12.4. Exporting the Back End
Now that we've decided that were going to use JSON, we need to figure out how we're going to make it accessible to the client. One option is to create a PHP page for each method; that page will look at the incoming POST data, transform it to PHP data types, call the method of the Ticket class, and then return its output formatted as JSON. An example of what this would look like for the login method is shown in Listing 12-3.
Listing 12-3. Login.php
Lines 23 include the classes needed for this page. We're using the JSON serializer code from HTML_AJAX, but any PHP JSON library would work. Line 5 reads the raw POST input, with lines 7 and 8 using the JSON Serializer class to decode it into a PHP object. On line 10, we create a new Ticket instance, calling the login method on line 12. We then send the output to the client on line 14, serializing it into the JSON format. An example HTML page that can be used to test this login page is shown in Listing 12-4.
Listing 12-4. Login.html
Lines 1315 set up an options object, which contains a JSON string that will be posted to the PHP page. Lines 1719 define the login function that makes the AJAX request. The request will be made to Login.php, calling the callback function when it's complete, and will pass in the serialized JSON string we set up in the options object. Line 23 provides us with a function to test it. When you run the login function, you will get output from the server that contains the user's profile, because that's what a successful login returns. An example is shown here:
user_id:1 username:josh email:email@example.com loggedIn:true
This system works by sending the JSON-encoded string to the server; in this case, the string would be like so:
The server decodes that into a PHP object that looks like this:
object(stdClass) var 'username' => 'josh' var 'password' => 'test2'
The login method on the Ticket class is called; this method returns a profile array. This array is turned into a JSON string, which is sent back to the client. This JSON string looks like this:
We could follow this same pattern to create a PHP page for every Ticket method, but fortunately, we have a simpler option. HTML_AJAX provides code to automatically expose the Ticket class's methods in a similar fashion. On the PHP side, this functionality is provided through the HTML_AJAX_Server class. An example of exporting the Ticket class is shown in Listing 12-5.
Listing 12-5. Server.php
Listing 12-6. LoginStub.html