<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>LornaJane</title>
	
	<link>http://www.lornajane.net</link>
	<description>Lorna Jane Mitchell's Website</description>
	<lastBuildDate>Wed, 01 Feb 2012 12:29:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/lornajane" /><feedburner:info uri="lornajane" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Building a RESTful PHP Server: Output Handlers</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/w1RgN9Gxeus/building-a-restful-php-server-output-handlers</link>
		<comments>http://www.lornajane.net/posts/2012/building-a-restful-php-server-output-handlers#comments</comments>
		<pubDate>Wed, 01 Feb 2012 08:15:15 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[output]]></category>
		<category><![CDATA[rest2]]></category>
		<category><![CDATA[RESTful]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1375</guid>
		<description><![CDATA[This is the third installment in my series about writing a RESTful web service in PHP (the previous entries are about understanding the request and routing it. It is probably the last one but there are a few other things &#8230; <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-output-handlers">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>This is the third installment in my series about writing a RESTful web service in PHP (the previous entries are about <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-understanding-the-request" title="Building A RESTful PHP Server: Understanding the Request">understanding the request</a> and <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-routing-the-request" title="Building A RESTful PHP Server: Routing the Request">routing it</a>.  It is probably the last one but there are a few other things I'd like to cover such as error handling, so I might keep adding to it, especially if I get any particular requests or interesting questions in the comments.  So far we've covered parsing requests to determine exactly what the user is asking for, and also looked at routing to a controller to obtain the data or perform the action required.  This post gives examples of how to return the data to the client in a good way. <span id="more-1375"></span></p>
<h3>Output Handlers Instead of Views</h3>
<p>We'll have as many output handlers as we have supported output formats.  The joy of having all the controllers return the data to<code> index.php</code> is that we can then add common output handling to all the data.  In our example system, we can remove that ugly <code>print_r</code> from <code>index.php</code> and instead detect which output format is needed and load the relevant view.  My code looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">    <span style="color: #000088;">$view_name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">ucfirst</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'View'</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">class_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$view_name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$view</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000088;">$view_name</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$view</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">render</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>The most simple example is a <code>JsonView</code> which looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> JsonView <span style="color: #000000; font-weight: bold;">extends</span> ApiView <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> render<span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Content-Type: application/json; charset=utf8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">echo</span> <span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>As you can see here, it's pretty simple!  We send the <code>Content-Type </code>header first to let the consumer know what's in the response, then we just encode the JSON and echo it out.<br />
To support other formats, you might loop over your array (remember it might be nested – things usually get recursive at this point for something like an XML format) and transform it into the new format.  Between two PHP systems, it might be simpler to support serialised PHP as a format as it is a little more verbose than the JSON.  </p>
<p>I also like to support HTML as an output format - for example the <a href="http://joind.in">joind.in </a>API does this; just go to <a href="http://api.joind.in">http://api.joind.in</a> with your browser and it will realise you're a web browser and return you the HTML version.  Joind.in is open source and since I wrote its RESTful API, it looks a lot like this one!  You can see the HTML output handler at: <a href="https://github.com/joindin/joind.in/blob/master/src/api-v2/views/HtmlView.php">https://github.com/joindin/joind.in/blob/master/src/api-v2/views/HtmlView.php</a></p>
<p>One format that I often get asked about is <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a> – so that other sites can make calls to the API from JavaScript and get around the cross-domain policy.  The way that I've implemented this in the past is to check for a parameter called "callback" with a request for JSON format, and if I get it, then just wrap the function around the response I would normally send.  I blogged about it <a href="http://www.lornajane.net/posts/2011/api-serving-jsonp">here</a> and again, this feature is in joind.in's codebase if you want to take a look.</p>
<p>Along with the data from the controller, it can also be useful to add some additional information to your output handlers, such as a count of how many top-level records were returned, and sometimes some pagination (I think I could write a whole other post about hypermedia and pagination - if you want it, leave me a comment).  This additional functionality should be added in the parent <code>ApiView </code>class - this just has a few helper functions which the various output formats can use if they want to.  Having it all central means that the responses will be very consistent across all the requests made to this service, and between formats. Consistency is absolutely the key to a good API so more shared functionality is always good.</p>
<p>There you have it, one functioning RESTful (ish! we skated over a few issues here, read the comments on all the posts in the series) server.  You can test it by calling your service from cURL or writing a script to consume it from PHP instead.  Since this was a simple tutorial there are some areas where I'd have liked to have gone in to more detail but it is already quite long-winded, so I'll stop there and if I get any good questions in the comments, I may add some followup posts!</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/w1RgN9Gxeus" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/building-a-restful-php-server-output-handlers/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/building-a-restful-php-server-output-handlers?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=building-a-restful-php-server-output-handlers</feedburner:origLink></item>
		<item>
		<title>PHP 5.4 Built In Webserver</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/W__8-tcGYQI/php-5-4-built-in-webserver</link>
		<comments>http://www.lornajane.net/posts/2012/php-5-4-built-in-webserver#comments</comments>
		<pubDate>Mon, 30 Jan 2012 08:16:24 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[php54]]></category>
		<category><![CDATA[webserver]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1406</guid>
		<description><![CDATA[One of the big features arriving with PHP 5.4 is the addition of a built-in basic webserver for use in development environments. Quite a few of the other scripting languages have something like this so I'm very pleased to see &#8230; <a href="http://www.lornajane.net/posts/2012/php-5-4-built-in-webserver">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>One of the big features arriving with PHP 5.4 is the addition of a built-in basic webserver for use in development environments.  Quite a few of the other scripting languages have something like this so I'm very pleased to see it in PHP.  Using a server like this makes it easy to quickly try out some scripts without needing to configure apache or really do anything much!  I had to look up a few things to get started, so I thought I'd write them down for posterity.<span id="more-1406"></span></p>
<h3>Get the Server Running</h3>
<p>The server runs when you pass the <code>-S</code> switch to PHP on the command line.  I had actually compiled PHP 5.4 alongside my existing PHP 5.3 installation, using <a href="http://www.lornajane.net/posts/2008/compiling-php-development-version">instructions from an earlier post</a>, and I just specified the full path to the version of PHP I wanted to run).  You then supply the server name and port number:</p>
<pre>
php -S localhost:8080
</pre>
<p>This gives some initial output, and then information about each request as it comes in:</p>
<pre>
PHP 5.4.0RC7-dev Development Server started at Sun Jan 29 16:40:49 2012
Listening on localhost:8080
Document root is /home/lorna/test
Press Ctrl-C to quit.
[Sun Jan 29 16:40:55 2012] 127.0.0.1:46713 [200]: /
[Sun Jan 29 16:40:55 2012] 127.0.0.1:46714 [404]: /favicon.ico - No such file or directory
</pre>
<p>By default, the current directory is your webroot and you can now request whatever files are here, and run PHP in the usual way.  You can also edit and save those files and re-request them without restarting the server, just as you would with a normal webserver (something I love about PHP).</p>
<p>The port number can be absolutely anything that you're not already using, I've seen examples with 8080, 8000 and even 1337 - you can use whatever you like.  If you pick a port that something else is using, you'll see an error <code>Failed to listen on localhost:8080 (reason: Address already in use)</code></p>
<h3>Changing the DocRoot</h3>
<p>If you want to run the server from one place and point it at a document root in another location, simply use the <code>-t</code> flag, followed by the path to the new docroot:</p>
<pre>
php -S localhost:8080 -t /var/www/awesomecode
</pre>
<p>Bear in mind that the webserver will run as the user you run this command as, so that user will need to have access to those files.  Webservers such as apache often run as other users, but this one will probably run as you.</p>
<h3>Routing Requests Like Apache Rewrite</h3>
<p>One immediate feature that I was looking for was the ability to redirect all incoming requests to <code>index.php</code>, which I usually do with an <code>.htaccess</code> file.  This webserver doesn't support those (although my good friend <a href="http://www.adayinthelifeof.nl/">Josh</a> has created <a href="https://github.com/jaytaph/htrouter">something pretty close</a>) but it does support a routing file.  There's a great example <a href="http://uk.php.net/manual/en/features.commandline.webserver.php">in the manual</a> of doing this which I used for reference.  You create a file <code>routing.php</code> in the same directory and this becomes your front controller, looking like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span>__DIR__ <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'REQUEST_URI'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// serve the requested resource as-is.</span>
   <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">include_once</span> <span style="color: #0000ff;">'index.php'</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span></pre></div></div>

<p>(this code taken entirely from <a href="http://news.php.net/php.internals/53870:">this internals post</a> as linked from the user contributed notes.  It works like a charm but I can't take the credit for it!)</p>
<p>This allows you to serve any files which are access by path in the usual way, but then redirect all other requests through to <code>index.php</code>.  It's such a common use case and I'm very pleased so see the examples already in the manual.</p>
<h3>Changing the Host Name</h3>
<p>You don't have to call your server localhost; in fact, you might choose to give it another name and access it from other machines.  To do this, simply add the new server name into <code>/etc/hosts</code> (or the equivalent for your system) and then start the server with the new name (I use my computer's name)</p>
<pre>
php -S taygete:8080
</pre>
<p>This means that you can set up the same alias for another user and they can access your server - very neat!</p>
<h3>Notes About the PHP Web Server</h3>
<p>This makes a very neat quick way of throwing up a test site for a particular document root without any need to reconfigure apache or set up anything else.  I'm using it to try out a few PHP 5.4 features without switching versions of PHP in and out of apache, and it works really well for that.  It is only recommended as a development tool however, and isn't intended for production use.  That said, it's a nice addition to the ever-impressive toolset of PHP and I'm happy to have it.</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/W__8-tcGYQI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/php-5-4-built-in-webserver/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/php-5-4-built-in-webserver?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=php-5-4-built-in-webserver</feedburner:origLink></item>
		<item>
		<title>Building A RESTful PHP Server: Routing the Request</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/1Ud4VTukyYc/building-a-restful-php-server-routing-the-request</link>
		<comments>http://www.lornajane.net/posts/2012/building-a-restful-php-server-routing-the-request#comments</comments>
		<pubDate>Mon, 23 Jan 2012 11:07:36 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[rest2]]></category>
		<category><![CDATA[RESTful]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1373</guid>
		<description><![CDATA[This is the second part of a series, showing how you might write a RESTful API using PHP. This part covers the routing, autoloading, and controller code for the service, and follows on from the first installment which showed how &#8230; <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-routing-the-request">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>This is the second part of a series, showing how you might write a RESTful API using PHP.  This part covers the routing, autoloading, and controller code for the service, and follows on from <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-understanding-the-request" title="Building A RESTful PHP Server: Understanding the Request">the first installment</a> which showed how to parse the incoming request to get all the information you need.<span id="more-1373"></span></p>
<h3>Routing to Controllers</h3>
<p>In this setup, we'll have models, controllers and ... <strong>output handlers</strong>.  It's not really a view, because all we will do is transform the data to a given output format.  More on that later on - for now we will return the data we fetch in the controller back to index.php, and dump it out so we can inspect it.</p>
<p>For RESTful routing, each thing in the system is considered as a<strong> resource</strong>, and it has a unique resource identifier (or URI) to represent it.  In this example system, we have users and groups.  Each resource belongs to a <strong>collection</strong>, which is the level above the resource – I usually think of files being in directories when I think of resources belonging to collections.</p>
<p>So for an incoming GET request to <code>/users</code>, we will return a list of users as this is the collection.  Within our application, this means calling the<code> getAction()</code> on the <code>UsersController</code>, so <code>index.php</code> now looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// route the request to the right place</span>
<span style="color: #000088;">$controller_name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">ucfirst</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url_elements</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'Controller'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">class_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$controller_name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$controller</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000088;">$controller_name</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$action_name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strtolower</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$verb</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'Action'</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$controller</span><span style="color: #339933;">-&gt;</span><span style="color: #000088;">$action_name</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>At this point, you'll write a controller and model that will look hauntingly familiar from all the other MVC systems you've ever written!  Before we do that though, let's talk about architecture and autoloading.</p>
<h3>Designing and Loading Classes</h3>
<p>Working with classes gets much easier if you put them in reliable places and call them reliable names.  If you do, you can autoload them and avoid all those tedious <code>require()</code> statements.  My directory structure looks like this:</p>
<pre>
.
├── controllers
│   ├── MyController.php
│   └── UsersController.php
├── index.php
└── models
</pre>
<p>The users controller is in the <code>controllers</code> directory, and it inherits from a shared parent controller called <code>MyController</code>.  I have no idea what will go into here, but from experience, I recommend that both models and controllers should inherit from a shared parent - as will our output handlers (because we don't have views) later on.  You can see that the controllers are reliably found in the controllers directory, called something ending in <code>*Controller.php</code>.  This makes it simple to add to an autoload rule: here's mine, which lives at the top of <code>index.php</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">spl_autoload_register</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'apiAutoload'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">function</span> apiAutoload<span style="color: #009900;">&#40;</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/[a-zA-Z]+Controller$/'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">include</span> __DIR__ <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/controllers/'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$classname</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/[a-zA-Z]+Model$/'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">include</span> __DIR__ <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/models/'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$classname</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/[a-zA-Z]+View$/'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">include</span> __DIR__ <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/views/'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$classname</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Hopefully this is simple enough to follow; if the classname ends in "Controller", look in the controllers directory; if it ends in "Model" look in the ... you get the picture.  Using very predictable naming and an autoload means that PHP will always find our classes easily (and we'll find them too when we are maintaining the system).</p>
<h3>The RESTful Controller</h3>
<p>This section is the part where you already know all you need to know!  At least, if you've used MVC before, and you've ever written a controller, then the controller in your RESTful application will look a lot like the one in any other!  It will talk to the model to fetch data, get everything in order and then pass it all on to a view.</p>
<p>In a RESTful system, the view is replaced by an output handler, so our controller will get everything assembled into an array and return it instead.  Our controllers deal with a variety of HTTP verbs, but will also need to parse out nested records.  Here's a super-simple example:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> UsersController <span style="color: #000000; font-weight: bold;">extends</span> MyController
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url_elements</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$user_id</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>int<span style="color: #009900;">&#41;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url_elements</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url_elements</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url_elements</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'friends'</span><span style="color: #339933;">:</span>
                    <span style="color: #000088;">$data</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;message&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;user &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$user_id</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;has many friends&quot;</span><span style="color: #339933;">;</span>
                    <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
                    <span style="color: #666666; font-style: italic;">// do nothing, this is not a supported action</span>
                    <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000088;">$data</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;message&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;here is the info for user &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$user_id</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$data</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;message&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;you want a list of users&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$data</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> postAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$data</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">parameters</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$data</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'message'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;This data was submitted&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$data</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In the <code>getAction()</code> we show some handling of requesting specifc resources and elements within those as well as just the collection; there is a very simple <code>postAction()</code> shown here too and the <code>postAction()</code> and <code>deleteAction()</code> would follow the same themes.  You would only declare all of these if you want to actually support those actions over your API.  For example, you might choose not to allow edit or delete of records, depending on your application.</p>
<p>At the moment, you have a working system, although all it does is <code>print_r()</code> the data it finds.  The next installment of the tutorial will deal with output handlers and how to send well-formatted data in a RESTful response.</p>
<p><b>Edit: </b>You can read the third entry in the series <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-output-handlers" title="Building a RESTful PHP Server: Output Handlers">here</a>.</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/1Ud4VTukyYc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/building-a-restful-php-server-routing-the-request/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/building-a-restful-php-server-routing-the-request?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=building-a-restful-php-server-routing-the-request</feedburner:origLink></item>
		<item>
		<title>Building A RESTful PHP Server: Understanding the Request</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/YBKCyAirLG8/building-a-restful-php-server-understanding-the-request</link>
		<comments>http://www.lornajane.net/posts/2012/building-a-restful-php-server-understanding-the-request#comments</comments>
		<pubDate>Thu, 19 Jan 2012 08:33:27 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[.htaccess]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[rest2]]></category>
		<category><![CDATA[RESTful]]></category>
		<category><![CDATA[verb]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1371</guid>
		<description><![CDATA[Once upon a time, what seems like a lifetime ago, I was away for a couple of weeks, and I wrote a series of posts about serving RESTful APIs from PHP to keep my blog going while I was away. &#8230; <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-understanding-the-request">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Once upon a time, what seems like a lifetime ago, I was away for a couple of weeks, and I wrote a series of posts about serving RESTful APIs from PHP to keep my blog going while I was away.  Fast forward a few years and those posts are outdated and still wildly popular - so I thought it was about time I revisited this and showed how I'm writing RESTful PHP servers today!</p>
<p>In the first part of this (probably) 3-part series, we'll begin with the basics.  It might seem boring, but the most important thing to get right with REST is parsing all the various elements of the HTTP request and responding accordingly.  I've put in code samples from from a small-scale toy project I created to make me think about the steps involved (should I put the code somewhere so you can see it?  Let me know).  Without further ado, let's dive in and begin by sending all requests through one bootstrap script:<span id="more-1371"></span></p>
<h3>Send Everything to index.php</h3>
<p>The first thing we need to do when we serve a RESTful response is the same as the first thing we do when we serve any other web page: figure out what the user actually wanted and how to deliver that.</p>
<p>To support the "pretty URLs" that we see in RESTful services (actually REST is way more complicated than that, but if I start talking about that as well, you'll still be reading in 3 hours' time!  Wikipedia has <a href="http://en.wikipedia.org/wiki/REST">rather a good explanation</a>), we'll add a <code>.htaccess</code> file to our directory which redirects all the requests to <code>index.php</code>.  My <code>.htaccess</code> file therefore looks like this:</p>
<pre>
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
</pre>
<p>This assumes you're using apache with mod_rewrite; the same thing can be achieved with other webservers.  With this in place, all requests to the service will arrive into the top of index.php – exactly the same way as most of the MVC (model-view-controller) frameworks work.  In fact, this whole RESTful service is going to be very MVC in style, because it makes sense to me to build things this way.</p>
<p>That said there are definitely other options; I've also worked with <a href="http://slimframework.com/">Slim</a>, which is a microframework.  This is neat as it lets you register a combination of URL and verb, and specify a callback that should be triggered when a matching request comes in.  It's lightweight and fast ... again, probably a post in itself if I start talking about it.</p>
<h3>Figure Out What Was Requested</h3>
<p>There are a few things we will want to know about what we have received here:</p>
<ul>
<li>The URL of the request</li>
<li>The method (GET, POST, PUT or DELETE) of the request</li>
<li>Any data that arrived with it</li>
</ul>
<p>Let's begin by looking at the first two elements; the code for these are common to all requests so we'll put it in <code>index.php</code> as all requests come here in the first instance.  I'm going to store all the details about the request in a Request object, which also has the functionality needed to parse all that information.  Here are the first few lines of that object:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Request <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$url_elements</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$verb</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$parameters</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">verb</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'REQUEST_METHOD'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url_elements</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'PATH_INFO'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We use the <code>$_SERVER</code> variable to pull information about the incoming request; the method is in <code>$_SERVER['REQUEST_METHOD']</code>.  The URL comes from <code>$_SERVER['PATH_INFO']</code> and we can split it into it's various parts using <code>explode()</code>.  From these parts, we'll see what the user requested and we'll work out how to route the request.</p>
<h3>Incoming Data</h3>
<p>To parse the incoming data, we'll need different approaches depending on what kind of request it was and what format the data is in.  We'll check the verb that was used, however for requests with a body (POST and PUT requests) we will also check the <code>Content-Type</code> header.  Bear in mind also that we will want to capture any URL parameters for POST, PUT and DELETE requests as well as for GET requests.</p>
<p>The parameters that arrive on the URL are relevant regardless of which verb was used; we'll always process these.  The script to do so is fairly straightforward, but do look out for <code>parse_str() </code>which writes into a variable you pass in by reference.  Once we've got that, we can deal with the body of the request, if there is one.  POST and PUT requests can have bodies with them, in which case we need to work out what format that data is in.  The example here supports both JSON and a standard form post, and we could add more cases to handle a wider selection of <code>Content-Type</code> headers by adding additional cases.  Here's the remainder of <code>Request::__construct()</code> and the method in this class for reading incoming variables:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">parseIncomingParams</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// initialise json as default format</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'json'</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">parameters</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'format'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">parameters</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'format'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> parseIncomingParams<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$parameters</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// first of all, pull the GET vars</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'QUERY_STRING'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #990000;">parse_str</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'QUERY_STRING'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$parameters</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// now how about PUT/POST bodies? These override what we got from GET</span>
        <span style="color: #000088;">$body</span> <span style="color: #339933;">=</span> <span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;php://input&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$content_type</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'CONTENT_TYPE'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$content_type</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'CONTENT_TYPE'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$content_type</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;application/json&quot;</span><span style="color: #339933;">:</span>
                <span style="color: #000088;">$body_params</span> <span style="color: #339933;">=</span> <span style="color: #990000;">json_decode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$body</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$body_params</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$body_params</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$param_name</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$param_value</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000088;">$parameters</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$param_name</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$param_value</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;json&quot;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;application/x-www-form-urlencoded&quot;</span><span style="color: #339933;">:</span>
                <span style="color: #990000;">parse_str</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$body</span><span style="color: #339933;">,</span> <span style="color: #000088;">$postvars</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$postvars</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$field</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #000088;">$parameters</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$field</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$value</span><span style="color: #339933;">;</span>
&nbsp;
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;html&quot;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
                <span style="color: #666666; font-style: italic;">// we could parse other supported formats here</span>
                <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">parameters</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$parameters</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>The <code>php://input</code> is the incoming stream to PHP.  For a "normal" web application we usually just use <code>$_POST</code>, which has already parsed this stream and decoded the form fields that were sent with the request.  For handling JSON data, PUT requests, and anything else that isn't a form POST, we need to parse the stream itself as shown here.</p>
<p>We also set the <code>format</code> property of the <code>Request</code> object - this is the format that we will send the output in.  You might have all kinds of logic to work out what that is, but for simplicity, we'll default to JSON.</p>
<p>At this point, we have the data and the request details all understood, and we are in a position to route into the controller and start writing the actual functionality – at last!  I'll be writing about the routing, autoloading, and controllers in the next installment.</p>
<p><b>Edit:</b> You can read the next part <a href="http://www.lornajane.net/posts/2012/building-a-restful-php-server-routing-the-request" title="Building A RESTful PHP Server: Routing the Request">here</a>.</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/YBKCyAirLG8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/building-a-restful-php-server-understanding-the-request/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/building-a-restful-php-server-understanding-the-request?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=building-a-restful-php-server-understanding-the-request</feedburner:origLink></item>
		<item>
		<title>SQL Joins with On or Using</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/hZoM4Ro-RCo/sql-joins-with-on-or-using</link>
		<comments>http://www.lornajane.net/posts/2012/sql-joins-with-on-or-using#comments</comments>
		<pubDate>Tue, 17 Jan 2012 08:25:14 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[tech]]></category>
		<category><![CDATA[join]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1364</guid>
		<description><![CDATA[I recently wrote a post about inner and outer joins, and a couple of people asked what the difference is between USING and ON. In a nutshell, you use ON for most things, but USING is a handy shorthand for &#8230; <a href="http://www.lornajane.net/posts/2012/sql-joins-with-on-or-using">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I recently wrote a post about <a href="http://www.lornajane.net/posts/2011/inner-vs-outer-joins-on-a-many-to-many-relationship">inner and outer joins</a>, and a couple of people asked what the difference is between <code>USING</code> and <code>ON</code>. <span id="more-1364"></span></p>
<p>In a nutshell, you use <code>ON</code> for most things, but <code>USING</code> is a handy shorthand for the situation where the column names are the same.</p>
<p>Consider this example dataset:</p>
<pre>
mysql> select * from pets;
+---------+---------+--------+-----------+
| pets_id | animal  | name   | owners_id |
+---------+---------+--------+-----------+
|       1 | fox     | Rusty  |         2 |
|       2 | cat     | Fluffy |         2 |
|       3 | cat     | Smudge |         3 |
|       4 | cat     | Toffee |         3 |
|       5 | dog     | Pig    |         3 |
|       6 | hamster | Henry  |         1 |
|       7 | dog     | Honey  |         1 |
+---------+---------+--------+-----------+
7 rows in set (0.00 sec)

mysql> select * from owners;
+-----------+-------+
| owners_id | name  |
+-----------+-------+
|         1 | Susie |
|         2 | Sally |
|         3 | Sarah |
+-----------+-------+
3 rows in set (0.00 sec)
</pre>
<p>To find out who has which pets, we would join the two tables together like this:</p>
<pre>
mysql> select owners.name as owner, pets.name as pet, pets.animal
    -> from owners join pets on (pets.owners_id = owners.owners_id);
+-------+--------+---------+
| owner | pet    | animal  |
+-------+--------+---------+
| Sally | Rusty  | fox     |
| Sally | Fluffy | cat     |
| Sarah | Smudge | cat     |
| Sarah | Toffee | cat     |
| Sarah | Pig    | dog     |
| Susie | Henry  | hamster |
| Susie | Honey  | dog     |
+-------+--------+---------+
7 rows in set (0.00 sec)
</pre>
<p>The example above uses the <code>ON</code> keyword, but since the columns we use to join are called <code>owners_id</code> in both tables, then we can instead put in <code>USING</code> as a shorthand.</p>
<pre>
mysql> select owners.name as owner, pets.name as pet, pets.animal
    -> from owners join pets using (owners_id);
+-------+--------+---------+
| owner | pet    | animal  |
+-------+--------+---------+
| Sally | Rusty  | fox     |
| Sally | Fluffy | cat     |
| Sarah | Smudge | cat     |
| Sarah | Toffee | cat     |
| Sarah | Pig    | dog     |
| Susie | Henry  | hamster |
| Susie | Honey  | dog     |
+-------+--------+---------+
7 rows in set (0.00 sec)
</pre>
<p>OK so it's a super-simple tip but until you see the different approaches laid out side-by-side, it can be confusing.  This <code>USING</code> trick is why you will often see fields named, for example, "user_id" when they are in the "users" table - then the shorthand can be used any time you join this user_id to any other user_id column.</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/hZoM4Ro-RCo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/sql-joins-with-on-or-using/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/sql-joins-with-on-or-using?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=sql-joins-with-on-or-using</feedburner:origLink></item>
		<item>
		<title>Which Basket Should A Developer Put Their Eggs In?</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/Vk7S2WamGMY/which-basket-should-a-developer-put-their-eggs-in</link>
		<comments>http://www.lornajane.net/posts/2012/which-basket-should-a-developer-put-their-eggs-in#comments</comments>
		<pubDate>Tue, 10 Jan 2012 06:57:41 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[work]]></category>
		<category><![CDATA[bootstrap]]></category>
		<category><![CDATA[product]]></category>
		<category><![CDATA[startup]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1359</guid>
		<description><![CDATA[The situation goes like this. Lots of excellent, capable people have great ideas for new software products. They are bootstrapping their venture, so they look for a developer who wants to give some time up front and receive a fair &#8230; <a href="http://www.lornajane.net/posts/2012/which-basket-should-a-developer-put-their-eggs-in">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>The situation goes like this.  Lots of excellent, capable people have great ideas for new software products.  They are bootstrapping their venture, so they look for a developer who wants to give some time up front and receive a fair (let's assume fair) share of the rewards once the product becomes successful.</p>
<p>The question is: as a developer, how do you know which of these products (I get about one tempting enquiry a month from what sounds like a real person who isn't building a social network) is a good bet? <span id="more-1359"></span></p>
<p>For my own products, that's easy.  I know what I want to build and while it's tough to be customer, project manager and developer all on my own, I can at least give it a shot.  I am self-employed and my products get time scheduled in just like all my other projects do - well, unless there's more interesting paying work to be had, in which case they tend to slide!</p>
<p>But what about those other excellent business people, who understand their market, have a great idea for a product, and are confident they can bring in enough paying clients to make the whole thing balance within a couple of years?  They should be able to launch their products too - but of course they need some technical skills on their team to do so.</p>
<p>For me, as a developer, I would love to get involved in some new ventures.  I enjoy building things that other people need, and as a freelancer I'm flexible enough to take on some side projects that won't pay me back directly.  I've been approached by perfectly sane-sounding local people who already run viable businesses and are looking to offer software products alongside those.  They know their market, their domain, and they know what they want.  So far, I've got enough work of my own that I haven't been sure enough to take the risk when it came past ... but will I ever know when to jump in and get involved?</p>
<p>What are your thoughts?  Have you joined in building something new with people you haven't worked with before?  On what kind of basis?  Are these kind of projects ever worth picking up?  Perhaps more interestingly, have you been burned and if so, what would you say were the warning signs now you have some hindsight?</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/Vk7S2WamGMY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/which-basket-should-a-developer-put-their-eggs-in/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/which-basket-should-a-developer-put-their-eggs-in?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=which-basket-should-a-developer-put-their-eggs-in</feedburner:origLink></item>
		<item>
		<title>Using lrnja.net Custom URL Shortener with Bit.ly</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/KZ3fJvOOnrU/using-lrnja-net-custom-url-shortener-with-bit-ly</link>
		<comments>http://www.lornajane.net/posts/2012/using-lrnja-net-custom-url-shortener-with-bit-ly#comments</comments>
		<pubDate>Wed, 04 Jan 2012 11:08:58 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[tech]]></category>
		<category><![CDATA[bit.ly]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[url]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1353</guid>
		<description><![CDATA[I'm a big bit.ly fan and recently I registered a shorter URL to use for short links - and I went for lrnja.net. I sat down to configure my new domain with bit.ly, and it was very straightforward (I'd almost &#8230; <a href="http://www.lornajane.net/posts/2012/using-lrnja-net-custom-url-shortener-with-bit-ly">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I'm a big <a href="http://bit.ly">bit.ly</a> fan and recently I registered a shorter URL to use for short links - and I went for lrnja.net.  I sat down to configure my new domain with bit.ly, and it was very straightforward (I'd almost say "designer-proof"! /me ducks).</p>
<ul>
<li>First: register your domain</li>
<li>Log in to your registrar's control panel and add an A record*</li>
<li>That's it!  In about 24 hours, you'll be able to shorten with your domain</li>
</ul>
<p>* or a CNAME if you want to use a subdomain of an existing domain.</p>
<p>Bit.ly has excellent instructions here: <a href="lrnja.net/bitlydomain">lrnja.net/bitlydomain</a></p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/KZ3fJvOOnrU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2012/using-lrnja-net-custom-url-shortener-with-bit-ly/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2012/using-lrnja-net-custom-url-shortener-with-bit-ly?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=using-lrnja-net-custom-url-shortener-with-bit-ly</feedburner:origLink></item>
		<item>
		<title>The Tree Command</title>
		<link>http://feedproxy.google.com/~r/lornajane/~3/UPfm_GupINs/the-tree-command</link>
		<comments>http://www.lornajane.net/posts/2011/the-tree-command#comments</comments>
		<pubDate>Thu, 29 Dec 2011 07:54:34 +0000</pubDate>
		<dc:creator>lornajane</dc:creator>
				<category><![CDATA[tech]]></category>
		<category><![CDATA[cli]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[tree]]></category>

		<guid isPermaLink="false">http://www.lornajane.net/?p=1350</guid>
		<description><![CDATA[Today I'm working on a little tutorial (about writing RESTful services, for this site) and I used the tree command to illustrate the file and directory layout of the project. I love this little command and use it frequently, but &#8230; <a href="http://www.lornajane.net/posts/2011/the-tree-command">Continue reading <span class="meta-nav">&#8594;</span></a><p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Today I'm working on a little tutorial (about writing RESTful services, for this site) and I used the <code>tree</code> command to illustrate the file and directory layout of the project.  I love this little command and use it frequently, but it isn't very well known so here's a quick example.<span id="more-1350"></span></p>
<p>As with most linux command line utilities, it does only one thing and it does it very well.  In this case, it shows the file structure.  For my work-in-progress project (which handily only has a few files so has fairly short output), it does this:</p>
<pre>
$ tree .
.
├── controllers
│   ├── MyController.php
│   └── UsersController.php
├── index.php
├── models
└── views

3 directories, 3 files
</pre>
<p>The . that was passed here is the name of the directory to generate the tree for; the dot means to use the current directory.  You can also pass switches limiting the depth of the listing, showing full paths to each file or directory, and omitting the indentations - as well as a large number of other options that seem less useful!</p>
<p>I use the tree command to put into blog posts, talk slides, and so on - I think it's clear and easy to read (especially because the toolchain I'm using for slides at the moment make most screenshots look decidedly chewed!), and also just to remind myself where all the various pieces of a project can be found.</p>
<p>Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist.  This post was originally published at <a href="http://www.lornajane.net">LornaJane</a></p>
<img src="http://feeds.feedburner.com/~r/lornajane/~4/UPfm_GupINs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lornajane.net/posts/2011/the-tree-command/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.lornajane.net/posts/2011/the-tree-command?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=the-tree-command</feedburner:origLink></item>
	</channel>
</rss>

