Simple REST server in PHP – Supports JSON & AMF

After building a couple of RESTful services using the Zend Framework, I decided to create a dead simple REST server that allowed me to skip all the features I didn’t need as well as a tons of classes that came with Zend Framework MVC. There are still useful features to add (XML support for example), but overall I’m quite happy with what I’ve come up with.

My solution, RestServer, is a JSON REST server, so far. It should be trivial to add support for XML or other formats, but there would have to be assumptions on what your object would look like in XML (XML-RPC style, your own custom XML format, etc). First we’ll look at the classes that you write to handle the requests, then we’ll look at how to tie it together in your index.php file.

REST Controllers

The RestServer class assumes you are using URL rewriting and looks at the URL from the request to map to the necessary actions. The map that gets a request from URL to class method is all in the doc-comments of the classes. Here is an example of a class that would handle some user actions:

class TestController
{
	/**
	 * Returns a JSON string object to the browser when hitting the root of the domain
	 *
	 * @url GET /
	 */
	public function test()
	{
		return "Hello World";
	}

	/**
	 * Logs in a user with the given username and password POSTed. Though true
	 * REST doesn't believe in sessions, it is often desirable for an AJAX server.
	 *
	 * @url POST /login
	 */
	public function login()
	{
		$username = $_POST['username'];
		$password = $_POST['password'];
		// validate input and log the user in
	}

	/**
	 * Gets the user by id or current user
	 *
	 * @url GET /users/:id
	 * @url GET /users/current
	 */
	public function getUser($id = null)
	{
		if ($id) {
			$user = User::load($id); // possible user loading method
		} else {
			$user = $_SESSION['user'];
		}

		return $user; // serializes object into JSON
	}

	/**
	 * Saves a user to the database
	 *
	 * @url POST /users
	 * @url PUT /users/:id
	 */
	public function saveUser($id = null, $data)
	{
		// ... validate $data properties such as $data->username, $data->firstName, etc.
		$data->id = $id;
		$user = User::saveUser($data); // saving the user to the database
		return $user; // returning the updated or newly created user object
	}
}

Let’s walk through the above TestController class to talk about the features demonstrated. First we’ll look at the test method. You’ll notice there is a new kind of doc-comment tag in the docblock. @url maps a URL to the method below it and is in the form:

@url <REQUEST_METHOD> <URL>

In this particular example, when someone does a GET on http://www.example.com/ (assuming example.com is where our service is located) it will print out:

"Hello World"

which is a valid representation of a string in JSON.

Moving on to the next method, login, we see the @url maps any POSTs to http://www.example.com/login to the login method. Getting data from a regular web-type POST is the same as any PHP application, allowing you to use your own validation or other framework in conjunction with this REST server. Sessions can also be kept if desired. Though keeping sessions isn’t true REST style, often all we want a REST server for is to serve up data to our ajax application, and it can be easier to just use sessions than something more RESTful.

Next we have our getUser method (you’ll notice that it doesn’t really matter what I name my methods because our @url directives define what URLs map to the method). You can see a couple of things here. First, we have multiple @url mappings for this method. And second, there is an odd “/:id” in that first URL mapping. The RestServer treats any “:keyword” placeholders as wildcards in the URL and will take that section of the URL and pass it into the parameter with the same name in the method. In this example, when hitting http://www.example.com/users/1234, $id will equal 1234. When hitting http://www.example.com/users/current, $id will equal null. It doesn’t matter what order your parameters are in, so long as they have the same name as the placeholder (:id and $id, :username and $username). You’ll also want to be sure to make your parameters optional ($id = null) when you have several URL mappings that don’t all require a parameter. Otherwise you’ll have an error thrown telling you that you didn’t pass in a required parameter.

One last thing to note in getUser is that this method simply returns a User object. This gets serialized into JSON (or potentially XML) and printed out for consumption by the application.

Finally we get to saveUser. You see here we have multiple URL mappings again. This time they also have different HTTP methods (POST and PUT) for creating and updating a user. The new thing here is the $data variable. This is a special keyword parameter that will contain the value of whatever was POSTed or PUT to the server. This is different than your regular web POST in that it doesn’t need to only be name-value pairs, but can be as robust as JSON, sending complex objects. For example, the body of a regular web POST, let’s say the login request, might look like this:

username=bob&password=supersecretpassw0rd

but POSTing a new user object for our saveUser method could look like this:

{ "username": "bob", "password": "supersecretpassword", "firstName": "Bob", "lastName": "Smith" }

So you’re able to allow POSTing JSON in addition to regular web style POSTs.

I call these classes that handle the requests Controllers. And they can be completely self-contained with their URL mappings, database configs, etc. so that you could drop them into other RestServer services without any hassle.

REST index.php

In order to get the whole server kicked off, you’ll want to create an index.php file, have your URL rewriting direct requests to it (another topic which you can learn about elsewhere), and create the RestServer and add controller classes to it for handling. RestServer will cache the URL mappings between requests using APC or a file to speed up requests. You won’t have to load every controller file on every request if you use autoload and this cache, only the one needed for the request. The cache only runs in production mode. Here is an example index.php file:

spl_autoload_register(); // don't load our classes unless we use them

$mode = 'debug'; // 'debug' or 'production'
$server = new RestServer($mode);
// $server->refreshCache(); // uncomment momentarily to clear the cache if classes change in production mode

$server->addClass('TestController');
$server->addClass('ProductsController', '/products'); // adds this as a base to all the URLs in this class

$server->handle();

That’s it. You can add as many classes as you like. If there are conflicts, classes added later will overwrite duplicate URL mappings that were added earlier. And the second parameter in addClass can be a base URL which will be prepended to URL mappings in the given class, allowing you to be more modular.

You can view the RestServer class, copy it and use it for your own purposes. It is under the MIT license. Features to be added include XML support and HTTP Authentication support. If you make this class better please share your updates with everyone by leaving a comment. I will try and keep this class updated with new features as they are shared. I hope you enjoy!

I changed the title of this post to remove the AMF portion but was asked to cover it, so I will quickly talk about the AMF support. RestServer supports the AMF format in addition to the JSON format. This is a binary format used by Adobe Flash in their remoting services, but because their remoting services are not RESTful, you can’t use classes such as RemoteObject with REST.

In order to use the AMF format with this service, you’ll need to have the Zend Framework in your classpath so that the classes to serialize and deserialize AMF are present (e.g. Zend/Amf/Parse/Amf3/Serializer.php). Then you’re ready so server up AMF. The way you consume AMF in Flash is using URLLoader or URLStream to load the data and ByteArray to convert it into an object. To tell the server you want AMF rather than JSON your URLRequest object will need to add an Accept header of “application/x-amf”. Below I will show you how this could be done.

public function getUser():void
{
	var loader:URLLoader = new URLLoader();
	loader.dataFormat = URLLoaderDataFormat.BINARY;
	var request:URLRequest = new URLRequest("http://www.example.com/users/current");
	request.requestHeaders.push(new URLRequestHeader("Accept", "application/x-amf"));
	loader.addEventListener(Event.COMPLETE, onComplete);
	loader.load(request);
}

private function onComplete(event:Event):void
{
	var loader:URLLoader = event.target as URLLoader;
	var byteArray:ByteArray = loader.data as ByteArray;
	var user:Object = byteArray.readObject();
	// do something with the user
}

You can even make your PHP objects cast into their actionscript equivalents using the $_explicitType property or getASClassName method in PHP as defined in the documentation and by using registerAlias in Flash.

Good luck and let me know if you end up using it!

Update: I am including an example .htaccess file for anyone who might need it. It will only rewrite requests to files that don’t exist, so you can have images, css, or other PHP files in your webroot and they will still work. Anything that would give a 404 will redirect to your index.php file.

DirectoryIndex index.php
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteRule ^$ index.php [QSA,L]
	RewriteCond %{REQUEST_FILENAME} !-f
	RewriteCond %{REQUEST_FILENAME} !-d
	RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

Update 2: I’ve put the code for RestServer up on github at https://github.com/jacwright/RestServer. It has some changes and may not work exactly like I’ve described here in this post. Be sure to read the documentation, when I get around to writing it. ;)

Flight Framework Highlights

The Flight Framework is basically a collection of great utilities and independent tidbits that are organized to help us build our application. So I thought I’d make a call out to all the great standalone features in Flight, tell what they are, and leave it to another day to go more in depth on them.

  1. Fix for abstract classes
    The tiny static classes in the flight.error package allow you to ensure an abstract class is not instantiated and that abstract methods are overriden.
  2. Registry
    A global registry to store objects or data that anything in an application can have access too.
  3. Reflection
    The “Type” class handles all your reflection needs, including caching the expensive describeType calls and helping pull out needed metadata.
  4. Nice base for models
    The ValueObject class is a lazy IEventDispatcher that implements an equals() and clone() method which will work with all subclasses.
  5. ValueObjectEditor
    This nifty utility lets you “edit” a ValueObject and then either commit the changes or revert them. Great for dialogs that let ValueObjects be changed but can then either Cancel or Ok the change.
  6. AS3 ArrayContainer
    When working in an AS3 project, it would be nice to know when an array is changed, but Flex’s ArrayCollection brings in half the framework when referenced. This little guy is the little brother AS3 has been wishing for.
  7. Services
    Some common services (RPC services, e.g. remoting, HTTP, etc.) that can be used in Flex or AS3. Much smaller than Flex’s built in services.
  8. Configuration
    Config lets you define your application configurations in the app, an XML file, SharedObjects, and even the URL. Not only that, you can have multiple sources with some overriding others, and it is all accessible to your classes through a global config property. Super neat!
  9. Undo framework
    With CommandHistory and all the command interfaces available, you can build undo-redo into your application without using any of the rest of Flight. Way, way awesome.
  10. Weak-referenced binding
    Using the Bind class you can create faster, smaller, and weak-referenced binds. With two-way deep binds and being able to use in AS3-only projects without importing half the Flex framework, this is my favorite nugget.

None of the above pieces references any of the others. They can all be used independently in your own frameworks or applications. That’s my favorite part about Flight, is I can use it 100% if I want to, but if I can’t that doesn’t mean I have to give up my favorite features. I could use any/all of the above with any other framework, AS3 only, or Flex.

ooCommerce Help

We are calling for developers who would like to join in on a fun object oriented PHP 5 ecommerce project entitle ooCommerce. Please email me or leave a comment if you would like to be a developer on this project or help in any way. The project is hosted at SourceForge and currently only has downloads for the template system it will be using, Arras Template. Arras Template has a website at www.arrastemplate.org. We (actually just myself right now) hope for this to be a good learning experience for others and are blogging about our design decisions how we are putting it together along the way. This way it can be more of a case study in progress for others to learn in a more of hands-on way about object oriented programming. Anyone is invited to help out, whether they know object oriented programming or not. If OOP isn’t a strong point, then you can just help coding (with guidance if desired). If it is a strong point, then you can help in the design process as well and post some blog posts too. I can do the design, database, classes, and all, but it would be a better project with more minds at work on it. It will also be finished sometime this century. Thank you for your help.

ooCommerce – A Deeper Look, More Decisions

We’ve broken down our system down into some general parts already. Now it’s time to make some decisions on more specific pieces of ooCommerce and break the system down into some main objects.

What’s in our Model

Well, first off, we know we need a database to store all of our store’s data. We’ll put off the database schema for now. But what we do need to decide is what database to use. And if we want to support several databases (which we do), what should we do to abstract the databases so that we use the same API no matter which database we use.

There are a few object-oriented options out there. My favorite is Creole, a PHP 5 database abstraction layer which has a nice interface. There is also PEAR’s DB which I’ve actually never used and have heard good things about. The good things about these are that they’re already built and they are actively developed which means others are fixing the bugs and adding features so we don’t have to. However, they are large, and the API of Creole is more of what Java programmers are use to and not what PHP developers are use to. We could also create our own object oriented abstraction layer. It would be smaller and use the API we want. Much more simple code. What do you think we should do?

The rest of the model would include the following list of objects, plus maybe a few we havn’t thought of yet:

  • Customer
  • Address Book
  • Address
  • Payment (stored)
  • CustomerGroup
  • Order
  • OrderItem
  • PaymentMethod
  • DeliveryMethod
  • Product
  • ProductReview
  • ProductSpecial
  • Catalog
  • Category
  • ShoppingCart
  • Translator
  • Pages
  • Content
  • Administrator
  • Report

There of course will need to be an object type for each method of payment and other additions like that. But I think we’ve got a pretty good layout here. We may think of other things later, especially when we want to add features.

How Will We Control Our Model

The controller part of our system could be pretty simple, or pretty elaborate. It all depends on what we value the most. If we like simple the best, we can just have a bunch of PHP pages that our use will go to, they will run the code they need to run, using the model objects, and then they will pull in a template and output the results. The URLs for these will be the name of the files, plus any parameters passed in the URL. These will be pretty procedural, although we could make them into classes to keep it object oriented. Another option is to push for search engine optimization by building our system with URLs that represent the page being displayed. If we go simple, we will have a “product.php?id=10” or “product.php?name=james_bond_movie” displaying our products. If we choose the more complex controller we would have “products/james_bond_movie” be our URL, which ranks it higher on the search engines. To do this we would need to use mod_rewrite with Apache and set up our scripts to handle these URLs. But it is very do-able. Do we want full-featured, or do we want simplicity? The value of ooCommerce will be higher with better features to it’s users.

Gotta See The View

There are a million and one template systems out there (I wrote the 1,000,001 template system) and most very similar. Smarty is the most popular it seems. And most are similar to Smarty except less features or slower. I happen to be partial to my templating system, Arras, which is different from most. It is also fast, and small, and fun to use, and easy for designers to do design on. So, I would like to use Arras.

So, what are your thoughts? Please give feedback on the following design decisions. We would love to get input.

  • What database abstraction layer should we use?
  • Any additional classes I forgot in the model?
  • Go for a simpler controller, or nicer URLs?
  • Use Arras for the template system or something else?

ooCommerce – The Overall Picture

So, we’re going to build ooCommerce, an ecommerce solution, an open source one. What pieces are involved? What are the major components of the system? Let’s get this organized using a top down approach.

Every ecommerce system has a few major parts in common. One is the catalog. This is where we can browse and search for the products. Then, we have the shopping cart. This is where we put the products when we want to buy them. We have our checkout, which is the process where we can purchase what is in our shopping cart. And lastly, many systems including ours will have a customer account section, where we can view our past orders and get support. Actually, we are fogetting a major part of the system. The administrative section. This can sometimes be the largest section and will help us organize the catalog, oversee orders, configure the system, and all the other administrative tasks associated with running an ecommerce store. Here are the “main sections.”

Main Ecommerce Sections

We will be storing many of the store’s information in a database. So we will need a database package (when I say package, it might be one class or a group of classes, we can figure out which later). We also want to keep the HTML and style of the site seperate from the code as much as possible so that it can change. This is a very important piece that osCommerce has not done well in. It can be very difficult to reskin osCommerce. So we will have a template package. We want to model an actual store in our code for a simpler and easier to code/understand system. This part will be the model and will be the one to interact with the database. Finally, we need something that takes the pages or actions of our store user, puts together the model information and the templates, and gives it back to our user. This will be our controller. So, we have a model, view, controller system we will be making. It will give us greater flexability. Here are the “MVC sections.”

Model View Controller Sections

The MVC (model, view, controller) sections aren’t different from the main sections described above. Rather, they are another way of looking at our system. We will have a customer class (from the model) used in the admin section, the shopping cart section, the order section, and the customer account section. The main sections above indicate the sections of the website, and the MVC sections indicate the different layers of code we will use in the website.

Right now we haven’t gotten to our classes yet. We’ve just been breaking the system up into smaller pieces. These may be organized into folders of classes or they may just be for our own reference.

We have successfully broken down the system one level. We will look at breaking down the system into small parts next time. We are on our way to a successful ecommerce solution.

Tutorial? How About a Project!

In writing the articles on object oriented programming I have stuck with theory. After all, it is not language specific and takes less space to say what there is to say. However, I have been asked by serveral to provide a tutorial or include examples on object oriented code. Well, I’ve decided to do something more. My good friend Andrew Branch has pointed out many times before that we learn better when we do things ourselves. And so, in that spirit, we will start a new full-fledged project together. I will write along as we develope it about how we should try to do things, so we can more fully understand object oriented principles. And we can all write the code for it.

The Project

Going back to my roots, I learned to program by hacking on osCommerce code. I wanted to make my own ecommerce site and run my own buisness. It was then that I discovered how enjoyable programming was and stuck with that instead. The problem with osCommerce is, however, that it is very procedural. It has SQL queries inline with the HTML on it’s pages. It uses functions to output pixel images. It requires a lot of hacking to modify. It is an adequate example of what you might call “spaghetti code.”

ooCommerce

We will be starting a new open source project that will implement all the features of osCommerce, but in a better way. And hopefully, since this will be more extensable, we can add many new features. We can call this project ooCommerce for object oriented ecommerce. I have already purchased the domains oocomerce.com, .net, and .org so that we may, eventually, have our own site for it. And I have submitted it to Sourceforge for pending approval. The benchmark of features we will be aiming for is listed on osCommerce’s site. And, because we are going full out object oriented, we will be using PHP 5. I am sorry if you were hoping for PHP 4, but in order to teach better OOP principles, and because PHP 4 is such a hack in terms of OOP, that’s what we need to use.

I hope ooCommerce will be, if nothing else, a great learning experience. Instead of a little pointless tutorial on saying “hello world” in an object oriented manner, we will actually create a full-featured system as our tutorial, implementing all that we’ve learned previously. We will look at planning this project out next week, so stay tuned.

Next Page »