<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Gen X Design &#124; Ian Selby</title>
	<atom:link href="http://www.gen-x-design.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gen-x-design.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Fri, 15 Jan 2010 21:41:43 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>More On Cloud Computing For PHP Developers</title>
		<link>http://www.gen-x-design.com/archives/more-on-cloud-computing-for-php-developers/</link>
		<comments>http://www.gen-x-design.com/archives/more-on-cloud-computing-for-php-developers/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 16:40:13 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=341</guid>
		<description><![CDATA[A while back, I wrote an article on the importance of cloud computing.  A few people posted some good comments and feedback, but last night I got such a long and well thought out comment that I thought it deserved it&#8217;s own post.  So, without further adieu, here are the thoughts of Daniel [...]]]></description>
			<content:encoded><![CDATA[<p>A while back, I wrote an <a href="http://www.gen-x-design.com/archives/the-importance-of-cloud-computing-for-php-developers/">article</a> on the importance of cloud computing.  A few people posted some good comments and feedback, but last night I got such a long and well thought out comment that I thought it deserved it&#8217;s own post.  So, without further adieu, here are the thoughts of Daniel Kadosh.<br />
<span id="more-341"></span><br />
Sharing my experience with a PHP app on EC2, which receives thousands of XMLs daily, parses them into a database, and has a web GUI to produce reports and graphs.</p>
<h2>If you have a simple website, why go Cloud?</h2>
<p>If you have a single-server setup and don&#8217;t want/need all the scalability you should at least price out a cloud provider. To me, having FULL backups being a no-brainer (Amazon can take filesystem snapshots in under 3 seconds), and being able launch a new server &#8212; in case the current one dies &#8212; within 3-15 minutes (my experience) are the biggest benefits. How long would that take with a dedicated hosting provider while your customer(s) are yelling at you on the phone?  And restoring a dump, tar, rsync or mysql dump once your new server is up?</p>
<p>There are 2 key tools I use to manage my servers on Amazon.<br />
ElasticFox:<br />
You&#8217;ll want the ElasticFox  plugin for Firefox to help you see and control stuff on Amazon, as it&#8217;s a bit better than the AWS GUI &#8212; for most things. Also overlaps in basic functionality with RightScale (below), but is more real-time.<br />
RightScale:<br />
To help with ALL sysadmin stuff, you can get and use for production a free &#8220;developer&#8221; account with RightScale, which puts together Linux images and has all sorts of startup scripts for common LAMP setups, great wikis, the works. It&#8217;s 3/4 of the way between &#8220;install Linux yourself&#8221; and cPanel-based shared hosting systems.  They support Amazon, GoGrid and I think Rackspace too.</p>
<h2>Why Amazon?</h2>
<p>In my research, Amazon still remains, BY FAR, the most advanced (in features) IaaS cloud provider. Couple it with RightScale and you get pretty much all the automation you need, including logging, alerts, auto-scaling (spin-up or down servers based on load), etc.  Amazon keeps on adding features, seemingly on a monthly basis, and they very much listen to what customers want.  They recently added &#8220;huge&#8221; servers with up to 64GB of RAM and 8 CPUs, and the ability to hold your root partition on non-volatile storage (used to be that once you shut down your machine, you lost the contents of root &#8212; not a big deal to work around anyways, since my data is on persistent EBS disk volumes).</p>
<p>One of my requirements was to be able to host things in Europe, to address EU privacy legal issues &#8212; &#8220;EU data must be hosted in the EU&#8221; &#8212; so Amazon is one of the few (only?) cloud providers that has a datacenter there.<br />
I was also concerned about disaster recovery, and Amazon seems to have more geographically-disperse datacenters than others. Couple that with their S3 storage redundancy and available from anywhere, and you&#8217;re covered.</p>
<h2>Re-think your architecture in a cloud:</h2>
<p>Just from scaling purposes, you need your applications to be able to recover/redirect things appropriately when adding or removing a database or web server from your deployments. The same can be said to address high-availability or disaster recovery. I had to re-think many assumptions about a given server being up, or even at the same IP address, so can&#8217;t hard-code these things. There are &#8220;always available&#8221; services that a cloud provider gives you to store these settings &#8212; Amazon has SimpleDB, or their storage service S3, both of which are highly redundant &amp; available.</p>
<p>Scale horizontally (add more servers), not vertically (add more RAM/CPU) is the key mantra in cloud computing. It&#8217;s a different mindset to have in architecting your application. You can, and sometimes should, take it to the extreme of making each server do just 1 thing, particularly if you have to process a lot of data. The typical example of this is a website that allows users to upload video, which has to be down-scaled and put into a database or better yet into the cloud storage service (like Amazon S3). So you&#8217;d have a queue system (see Amazon SQS for a solution) that has your front-end web server put the raw video in the queue, sends a message to the processing server, which all it ever does is &#8220;check queue, process item if found, repeat&#8221;.</p>
<p>Yes, there are some quirks to work around in cloud providers, but they&#8217;re worth it for me if nothing else for peace of mind. I wish I could have &gt;1 IP address per server on Amazon.</p>
<p><strong>About the Author</strong><br />
As I said, this post is actually a comment contributed by Daniel Kadosh. Daniel works for Affinegy, Inc., a software company in Austin, TX<br />
<a href="http://www.affinegy.com" target="_blank">http://www.affinegy.com</a></p>
<p><em>What are your thoughts?  If you&#8217;ve got an opinion, share it, and I may even give it the same attention I did for Daniel <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/more-on-cloud-computing-for-php-developers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Recompiling PHP 5.3 On Snow Leopard With Freetype Support</title>
		<link>http://www.gen-x-design.com/archives/recompiling-php-5-3-on-snow-leopard-with-freetype-support/</link>
		<comments>http://www.gen-x-design.com/archives/recompiling-php-5-3-on-snow-leopard-with-freetype-support/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 19:19:46 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Freetype]]></category>
		<category><![CDATA[PHP 5.3]]></category>
		<category><![CDATA[Snow Leopard]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=329</guid>
		<description><![CDATA[OK, so this article probably doesn&#8217;t have a ton of mass appeal, but since upgrading to Snow Leopard I&#8217;ve run into a major issue with the way PHP is compiled in this distribution.  Overall, I&#8217;m incredibly satisfied with the way everything&#8217;s set up by default in Snow Leopard (PHP 5.3 with bundled GD, mysqlnd, [...]]]></description>
			<content:encoded><![CDATA[<p>OK, so this article probably doesn&#8217;t have a ton of mass appeal, but since upgrading to Snow Leopard I&#8217;ve run into a major issue with the way PHP is compiled in this distribution.  Overall, I&#8217;m incredibly satisfied with the way everything&#8217;s set up by default in Snow Leopard (PHP 5.3 with bundled GD, mysqlnd, etc.), but the big glaring hole in everything was the lack of Freetype support.  I&#8217;ve been working on a graphing library for my day job, and as such found the need to place text in my images (strange, right?).  Anyway, I finally took the plunge and figured out how to get that sucker compiled in there.  Here&#8217;s what you have to do&#8230;<br />
<span id="more-329"></span><br />
Basically, what we&#8217;re going to do is recompile PHP 5.3 exactly the same as it came, but with proper Freetype support.  Before we get into anything, here&#8217;s a few disclaimers:</p>
<ul>
<li>This worked for me&#8230; it may not work for you.  If you never make it to the &#8220;make install&#8221; step of the PHP build, you won&#8217;t screw up your system so you can feel relatively safe trying this.  However, I can&#8217;t support you if something goes wrong.  Don&#8217;t worry tho, you shouldn&#8217;t run into many issues <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>The steps in this tutorial are munged together from various other sources on the web.  I&#8217;d like to credit these people if possible, but I don&#8217;t have a list of all my various sources&#8230; if your stuff is on here, lemme know and I&#8217;ll make sure you&#8217;re properly credited and linked to <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>You MUST have the xcode developer tools installed for any of this to work.  You&#8217;ll know right away if you don&#8217;t, as &#8220;make&#8221; will be an unknown command for you.  These are on your Snow Leopard install DVD if you don&#8217;t have them&#8230;</li>
</ul>
<p>OK, moving on&#8230;</p>
<h2>Download Source Files</h2>
<p>We&#8217;re going to need to grab a few things to get started.  So, fire up a terminal, and type in the following:</p>
<pre class="code">sudo mkdir /src
sudo chown [your username]:staff /src
cd /src
mkdir pcre
mkdir php
cd pcre
curl ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.7.tar.gz -O
cd ../php
curl http://www.opensource.apple.com/source/apache_mod_php/apache_mod_php-53/php-5.3.0.tar.bz2 -O
</pre>
<p>What we&#8217;ve got is the PHP 5.3 package from Apple, and the PCRE library&#8230; everything else we need is already on our system.  Let&#8217;s get compiling&#8230;</p>
<h2>Compile PCRE</h2>
<p>We need to compile PCRE into a local directory (not system-wide) so the PHP compiler has access to the headers it will need.  This is pretty easy, just run the following:</p>
<pre class="code">cd /src/pcre
tar -zxvf pcre-7.7.tar.gz
cd pcre-7.7
./configure --disable-shared --enable-static
make &#038;&#038; make install DESTDIR=/src/pcre/pcre-local
</pre>
<p>That&#8217;s it!  Now we can start playing around with PHP</p>
<h2>Compile PHP</h2>
<p>Basically, what we&#8217;re going to be doing here is recompiling PHP 5.3 with the same config parameters as it was originally built with, but changing the things we need for GD and PCRE.  It&#8217;s important that you follow all the steps outlined here, or you&#8217;ll get some weird compile errors.  Also, if you&#8217;re a bit uncomfortable about recompiling, remember that you&#8217;re not going to mess anything up until you actually run the &#8220;make install&#8221; command.  So, if the compile fails for any reason, your current PHP install isn&#8217;t going to get messed up in any way.</p>
<p>So, let&#8217;s get started:</p>
<pre class="code">cd /src/php
bunzip2 php-5.3.0.tar.bz2 &#038;&#038; tar -xvf php-5.3.0.tar
cd php-5.3.0</pre>
<p>Now, we&#8217;ll need to edit one file to fix a compile error we&#8217;ll run into.  Open /src/php/php-5.3.0/ext/iconv/iconv.c in your editor of choice, and head to line 186.  We need to change the line from:<br />
&#8220;#define iconv libiconv&#8221;<br />to<br />
&#8220;#define iconv iconv&#8221;</p>
<p>Once you&#8217;ve done that, we&#8217;re good to go.  Assuming you&#8217;re still in /src/php/php-5.3.0:</p>
<pre class="code">MACOSX_DEPLOYMENT_TARGET=10.6
CFLAGS="-arch x86_64 -g -Os -pipe -no-cpp-precomp"
CCFLAGS="-arch x86_64 -g -Os -pipe"
CXXFLAGS="-arch x86_64 -g -Os -pipe"
LDFLAGS="-arch x86_64 -bind_at_load"
export CFLAGS CXXFLAGS LDFLAGS CCFLAGS MACOSX_DEPLOYMENT_TARGET
./configure --prefix=/usr \
--mandir=/usr/share/man \
--infodir=/usr/share/info \
--disable-dependency-tracking \
--sysconfdir=/private/etc \
--with-apxs2=/usr/sbin/apxs \
--enable-cli \
--with-config-file-path=/etc \
--with-libxml-dir=/usr \
--with-openssl=/usr \
--with-kerberos=/usr \
--with-zlib=/usr \
--enable-bcmath \
--with-bz2=/usr \
--enable-calendar \
--with-curl=/usr \
--enable-exif \
--enable-ftp \
--with-gd \
--with-jpeg-dir=/usr/local/lib \
--with-png-dir=/usr/X11R6 \
--with-freetype-dir=/usr/X11R6 \
--with-xpm-dir=/usr/X11R6 \
--with-ldap=/usr \
--with-ldap-sasl=/usr \
--enable-mbstring \
--enable-mbregex \
--with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-mysql-sock=/tmp/mysql.sock \
--with-iodbc=/usr \
--enable-shmop \
--with-snmp=/usr \
--enable-soap \
--enable-sockets \
--enable-sysvmsg \
--enable-sysvsem \
--enable-sysvshm \
--with-xmlrpc \
--with-iconv-dir=/usr \
--with-xsl=/usr \
--with-pcre-regex=/src/pcre/pcre-local/usr/local</pre>
<p>If everything completed without error, you&#8217;re ready to compile (again, if this fails, nothing is messed up with your current PHP installation):</p>
<pre class="code">export EXTRA_CFLAGS="-lresolv"
make</pre>
<p>This will take a few moments, so go grab a coffee or something <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />   If this step completed properly (i.e you get some message about &#8220;don&#8217;t forget to run make test&#8221;), you&#8217;re ready to finish up.  One thing I like to do is back up my current php.ini file, but if you haven&#8217;t tweaked it (or created it for that matter), you don&#8217;t need to do this:</p>
<pre class="code">sudo cp /etc/php.ini /etc/php.ini.bak</pre>
<p>Now, you can install our fresh PHP build:</p>
<pre class="code">sudo make install</pre>
<p>That&#8217;s it!  Now, you can copy your old php.ini file back, and restart apache:</p>
<pre class="code">sudo cp /etc/php.ini.bak /etc/php.ini
sudo apachectl restart</pre>
<p>If you set up a phpinfo() somewhere in your doc root, you should now see something like the following in the GD section of it:<br />
<img src="http://www.gen-x-design.com/wp-content/uploads/2009/10/Screen-shot-2009-10-05-at-12.16.48-PM1.png" alt="PHP 5.3 GD with Freetype" title="PHP 5.3 GD with Freetype" width="585" height="307" class="alignnone size-full wp-image-338" /></p>
<p>Enjoy <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/recompiling-php-5-3-on-snow-leopard-with-freetype-support/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>I&#8217;m Not Dead, I&#8217;m Just Out of Ideas (For Now)</title>
		<link>http://www.gen-x-design.com/archives/im-not-dead-im-just-out-of-ideas-for-now/</link>
		<comments>http://www.gen-x-design.com/archives/im-not-dead-im-just-out-of-ideas-for-now/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 20:19:39 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=327</guid>
		<description><![CDATA[Just wanted to write a quick post to let everyone know I haven&#8217;t lost interest in writing or fallen off the face of the planet&#8230; I&#8217;ve just been incredibly busy with other things.  Also, frankly, I can&#8217;t think of anything compelling to write about.  I used to think it was important to try [...]]]></description>
			<content:encoded><![CDATA[<p>Just wanted to write a quick post to let everyone know I haven&#8217;t lost interest in writing or fallen off the face of the planet&#8230; I&#8217;ve just been incredibly busy with other things.  Also, frankly, I can&#8217;t think of anything compelling to write about.  I used to think it was important to try and get articles up at some set frequency, but I find that the quality of my stuff falls short if I&#8217;m forcing myself to do so.  Anyway, I&#8217;m basically now of the mind that I&#8217;ll write about stuff whenever I come up with something&#8230; could be twice a week, could be once in three months.  Part of my major hang-up is that I don&#8217;t like to write articles that cover topics that have been thoroughly covered elsewhere, unless I&#8217;ve got something new to add to the mix.</p>
<p>Now, all that being said, I&#8217;m more than happy to take suggestions from anyone if they&#8217;ve got them.  If there&#8217;s something you&#8217;d like to know more about, or you just have a cool idea for an article, drop me a line in the comments.  Otherwise, stay tuned for new stuff whenever I think of it <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />   Also, you can always follow me on twitter, or subscribe to my RSS feed as I post various interesting links and randomness in both places.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/im-not-dead-im-just-out-of-ideas-for-now/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The Importance of Cloud Computing for PHP Developers</title>
		<link>http://www.gen-x-design.com/archives/the-importance-of-cloud-computing-for-php-developers/</link>
		<comments>http://www.gen-x-design.com/archives/the-importance-of-cloud-computing-for-php-developers/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 20:33:41 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[development]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=318</guid>
		<description><![CDATA[You may (or may not) have noticed that there&#8217;s A LOT of talk about cloud computing these days.  The problem with all this chatter is that it&#8217;s incredibly hard to follow.  There seems to be a wealth of different definitions of just what cloud computing actually is, and not without good reason.  [...]]]></description>
			<content:encoded><![CDATA[<p>You may (or may not) have noticed that there&#8217;s A LOT of talk about cloud computing these days.  The problem with all this chatter is that it&#8217;s incredibly hard to follow.  There seems to be a wealth of different definitions of just what cloud computing actually is, and not without good reason.  The &#8220;cloud&#8221; is a pretty ambiguous term, and as such anything attached to it only makes the whole thing a little more ambiguous.  Rather than go off on a rant about how all this confusion is leading to a lot of misconceptions about various cloud-based services, let me clarify what I&#8217;m going to talk about.  This will not be a discussion of certain SaaS stuff living in the cloud (like gmail, twitter, etc.), but rather actual cloud-based computing services and why you need to be using them.<br />
<span id="more-318"></span></p>
<h2>What is Cloud Computing?</h2>
<p>So, before we get into the why, let&#8217;s go over the what a little bit more (if you&#8217;re familiar with services like EC2 or S3, feel free to skip this part).  In a nutshell, cloud computing is really nothing more than virtualized private servers on steroids.  Traditionally, if you wanted to host a site or app you would either get a shared hosting account somewhere, or get your own dedicated box (or many boxes).  This generally works fine, but there are a lot of drawbacks to the so-called traditional way of doing things.  We&#8217;ll get into this in a little bit, but for the moment we only need to know that these solutions involved actual physical servers.  A dedicated server is just that, a dedicated piece of hardware for you to use&#8230; shared hosting is similar in the fact that you&#8217;re merely a tenant on a dedicated server (you could relate it to renting an apartment vs. owning a home).  </p>
<p>Anyway, cloud computing is essentially the same as dedicated hosting, except for one very important distinction:  you&#8217;re not using a physical server, your server is virtualized. That&#8217;s it, it&#8217;s really that simple!  However, this simplicity has a lot of very important benefits that lead it to beat the hell out of any traditional hosting situation.  It also has one very significant draw-back as well.  We&#8217;ll get into these next&#8230;</p>
<h2>Why Cloud Computing is Awesome</h2>
<p>Before we get into any drawbacks of this &#8220;cloud&#8221; stuff, let&#8217;s go over all the great things about it.</p>
<h3>It&#8217;s Cheap</h3>
<p>Cloud hosting is super-cheap compared to traditional dedicated hosting.  A cloud-based server doesn&#8217;t take up space in racks, doesn&#8217;t required dedicated hardware, or any of the other costly stuff that physical servers require.  Instead, one uber-powerful server can host several virtual servers, thus cutting down on costs at the data center, which gets passed to us.</p>
<p>On top of that, a lot of cloud hosting providers only charge you for what you use.  If you only need a server for a few days / weeks for testing, you only need to pay for the time it was up and running.  No commitments, no monthly charges whether you use the server or not, nothing.  Awesome.</p>
<h3>It&#8217;s Reliable</h3>
<p>Early adopters of cloud hosting will tell you horror stories about their cloud servers randomly disappearing and other fun stuff like that, but this is no longer the case with any of the providers.  This simply doesn&#8217;t happen any more.  That aside, the fact that your server is virtualized adds a ton of other reliability benefits.  Think about it, you don&#8217;t have any physical RAM, CPU, or hard drives to fail.  Even better, the aforementioned uber-servers that your cloud server lives on take redundancy to the extreme, so there&#8217;s no reasonable worry about the host machine&#8217;s hardware failing, thus causing your server to fail.  To make matters better, if in the rare event that the host machine fails, guess what?  Your virtual server is simply (and quickly) moved to a server that doesn&#8217;t have issues.  How cool is that? </p>
<p>It get&#8217;s better.  Unlike shared hosting (which you should never use, which is another article I suppose) where your site shares resources with all the other shared sites on the server, you get dedicated resources.  Imagine you&#8217;re on a shared host and somebody else&#8217;s site gets a huge traffic spike&#8230; their site will start to consume a ton of server resources, which get robbed from your site.  With cloud hosting, this doesn&#8217;t happen.  You get a guaranteed share of ram, disk, and CPU&#8230; same as you would with a dedicated server.</p>
<p>Finally, backups of cloud servers are super-reliable and super-awesome.  With dedicated hosting, you can easily set up automated back-ups on your server, but those never back everything up.  You still have to write cron jobs to do database dumps as the automated backup stuff won&#8217;t ever touch an active database data file, and you still have to say what it is you want backed up outside of that.  With cloud hosting, your WHOLE SERVER is backed up.  Remember, it&#8217;s virtualized, so a backup is nothing more than a snapshot.  Like I said, super-awesome.</p>
<h3>It&#8217;s Fast to Set Up</h3>
<p>SInce everything&#8217;s virtual, you can usually get a cloud server up and running in minutes.  There&#8217;s no hardware to plug into a rack, no servers to purchase, none of that junk.  You just (essentially) tell the hosting provider you want a server, and they create it for you.  This means that you can create and destroy servers as you need them, without having to make all sorts of plans in advance or waiting around.</p>
<h3>It&#8217;s SUPER Scalable</h3>
<p>One of the biggest draw-backs with dedicated hosting (or shared for that matter) is that you can&#8217;t scale easily, or even at all.  You get a server with a certain amount of RAM and disk space, and whatever CPU happened to be installed, and you&#8217;re stuck.  If you want to add more RAM, you usually end up paying through the nose for it&#8230; same with disk space.  And if you want a newer CPU, you get a new server.</p>
<p>Imagine your app gets a traffic spike and your machine gets overloaded.  How fast can you get another server set up to accommodate the load?  At best, with dedicated hosting, 24 hours, and then you&#8217;ve still got to set everything up and possibly deal with load balancers, etc.  Say you go ahead and do that, and the traffic spike drops after a month.  What now?  You&#8217;ve got way more computing power than you need, and you probably can&#8217;t get rid of the extra server easily&#8230; so you&#8217;re stuck with it (more money, more problems).</p>
<p>Well, this doesn&#8217;t happen with cloud servers.  If you get a traffic spike, you simply scale the server up.  More often than not, you simply need more RAM to deal with high load on your server.  Guess what? Since your cloud server is virtualized, more RAM is only a matter of having the hosting provider allocate it to your machine.  This usually involves a few clicks in a web interface, and a few more minutes for the scaling to happen.  Even better, when you no longer need the extra resources, you can just as easily scale down.  No headaches, and you don&#8217;t need to spend a ton of money to do it (which also goes back to the cheapness of cloud hosting).</p>
<p>Even if more RAM won&#8217;t cut it (maybe you need another database server or something like that), spinning up new sites is easy.  Hell, you can usually clone your current server (or one of your servers if you have several) from one of your snapshots.  So, not only can you get a new server up in minutes, but it&#8217;s already got everything ready and running on it.  More awesomeness.</p>
<h2>The Drawback of Cloud Hosting</h2>
<p>Despite all the goodness we just went over, there&#8217;s one big problem with cloud hosting / computing.  You have to set everything up yourself.  There&#8217;s no control panel (unless you install one), nothing.  When you spin up a server, you get a root password and a clean OS install.  If you don&#8217;t know what you&#8217;re doing, or how to set things up, you&#8217;re in for a long and arduous set up process.</p>
<p>But things aren&#8217;t as bad as it seems.  There are a lot of really well-written tutorials out there, often written by the hosting provider, that will walk you through getting your servers set up however you need them to be.  Even better, there are also some really cool services in the works that will take care of this setup for you (one of which I&#8217;m working on&#8230; stay tuned <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ).  So, this issue is rapidly becoming moot, but it&#8217;s still important to mention and acknowledge.</p>
<h2>Why All This is Important to PHP Developers</h2>
<p>You are probably asking yourself why this matters to you as a PHP developer&#8230; and with good reason.  More often than not, the traditional ways of doing things have been more than adequate for us.  Very often, the &#8220;best practice&#8221; setup for development has been to set up a local development environment with XAMPP/WAMP/MAMP, and to buy cheap shared or dedicated hosting somewhere for the actual site / app to run in production on.</p>
<p>I, however, think this approach sucks.  As easy as stuff like XAMPP is, it&#8217;s always got shortcomings.  If you want to try and use any technology that isn&#8217;t bundled with these packages, you&#8217;re pretty screwed (try and set up memcache on windows&#8230; lemme know how that goes).  There are so many cool new technologies out there that I see many developers ignoring simply because there&#8217;s no easy way to work with them from a development perspective.  Honestly, are you going to waste a ton of time trying to recompile PHP to include the bundled GD libraries, or some other thing, or installing software like Image Magick, Sphinx, Memcache, APC, whatever?  It&#8217;s not always easy, so it&#8217;s rarely tackled.  Perhaps you want to play around with PHP 5.3 or MySQL 6, or Postgres, MySQL replication or something else because you&#8217;re curious&#8230; how do you do this locally?</p>
<p>If you&#8217;re savvy, your answer to me would probably be to set up a local VM with VMware or VirtualBox.  Not a bad answer, but those are a pain sometimes too.  Local VMs can take valuable resources from your machine, and if you&#8217;re using an IDE, you&#8217;re probably already short on RAM (especially those of you using eclipse or eclipse-based IDEs).  So you&#8217;ll turn these VMs on or off when you need them, but that&#8217;s also a pain.</p>
<p>Let&#8217;s take it one step further&#8230; You probably work on lots of different projects.  If you&#8217;re like me, you run these all against some local Apache installation in subfolders while you&#8217;re developing (i.e. localhost/projecta and localhost/projectb).  Well, that&#8217;s not a real representation of how things are going to run in production, which is never a good thing.  You probably also use SVN or Git (if you don&#8217;t use SCM for development, start.  Trust me, do it), and you probably just host that stuff locally.  This is also less than ideal.</p>
<p>I&#8217;m sure you see where I&#8217;m going with all this.  All these problems can be solved with cloud hosting.  I don&#8217;t feel like I need to go into great detail here, as these solutions should be pretty self-evident.  Think about it&#8230; if you want to play around with PHP 5.3 or some other new technology, you need only spin up a cloud server for a few days / weeks and do so.  It&#8217;s cheap, easy, and you won&#8217;t run the risk of borking whatever local dev environment you&#8217;ve got set up.</p>
<p>But there&#8217;s a bit more to it than that.  Say you want to test a migration from one version of something to another, or an upgrade process for an app you&#8217;ve written.  If you&#8217;ve got an environment set up in a cloud, you need only take a snapshot of your server&#8217;s current state and then attempt the migration / upgrade / whatever.  If something gets screwed up, revert to the snapshot and try again&#8230; that easy.  You can&#8217;t argue that this isn&#8217;t a much better alternative to trying to do this with a dedicated server or local dev environment.</p>
<p>Finally, it&#8217;s simply a better way to develop.  I&#8217;ve got a local XAMPP install that I use, admittedly, but I&#8217;ve also got several servers in the cloud.  All my wiki, source control, and other important dev-related stuff lives on a dev server I&#8217;ve got set up in the cloud.  It&#8217;s backed up, it works, and I&#8217;ve got total control over how it&#8217;s set up.  I&#8217;ve also got a few other dev / production servers set up (this site is running on one) for my various rails / php projects that I work on.  I can easily play around with new stuff without worrying about screwing anything up, I can keep all my development and testing properly isolated (I know people who run their dev and production environments on the same dedicated server&#8230; that&#8217;s playing with fire my friends), and everything just works.</p>
<h2>Getting Started</h2>
<p>So, how do you get started with the cloud.  Well, that all depends on you&#8230; if you&#8217;re comfortable with the command line and general setup / config / admin of *nix servers, you should just dive into it.  If you&#8217;re not (and there&#8217;s nothing wrong with that), you can either decide to learn, or sit tight for a bit.  Like I said, there are people (including myself) that are working on taking the configuration and setup management of cloud servers and making it nothing more than a few clicks on a control panel.</p>
<p>Either way, you really do need to get into the cloud as soon as you can.  Everything&#8217;s going to be moving in this direction (and already is in a lot of cases), and it&#8217;s also simply a better way to do things all around.  I haven&#8217;t even touched on the beauty of cloud hosting for production environments, which is another discussion altogether.</p>
<p>Anyway, I leave you with a few links to the most popular cloud hosting providers.  Feel free to shoot any questions / comments you may have my way in the comments!</p>
<ul>
<li><a href="http://aws.amazon.com/ec2/" target="_blank">Amazon EC2</a> &#8211; EC2 was the first major cloud computing offering, and it&#8217;s the most robust as far as service options (stuff like virtual load balancers, etc.).  They&#8217;re also a bit pricier than other providers, but they&#8217;re damn good</a></li>
<li><a href="http://slicehost.com" target="_blank">Slicehost</a> &#8211; Slicehost is just awesome&#8230; and cheap.  A server will cost you around $20 / month.  They&#8217;ve also got amazing articles to help you get pretty much anything you&#8217;d like set up on your server.  Highly recommend them</li>
<li><a href="http://www.rackspacecloud.com/" target="_blank">Rackspace Cloud</a> &#8211; Also an awesome service.  They are a bit cheaper than slicehost (around $12 / month to start), but are priced a bit more variably (slicehost is more of a set fee)&#8230; you pay per hour for the server plus bandwidth.  Rackspace owns the rackspace cloud (obviously) and Slicehost, so it&#8217;s really a matter of preference here.  I actually like the Rackspace Cloud a bit more merely for the pricing scheme since I spin servers up and down more frequently to play around with stuff</li>
<ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/the-importance-of-cloud-computing-for-php-developers/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>PHP Thumb 3.0 Released</title>
		<link>http://www.gen-x-design.com/archives/php-thumb-30-released/</link>
		<comments>http://www.gen-x-design.com/archives/php-thumb-30-released/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 19:23:21 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php thumb]]></category>
		<category><![CDATA[thumbnailer]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=309</guid>
		<description><![CDATA[
Well, it&#8217;s been a long time coming, but I&#8217;ve finally managed to get the next release of my PHP Thumbnailer library completed!  I&#8217;m also happy to announce that the project finally has its own website: http://phpthumb.gxdlabs.com.  I&#8217;ve put a lot of work into bringing the class up to date, making it extensible, and [...]]]></description>
			<content:encoded><![CDATA[<div style="text-align: center"><img style="margin-top: 10px; margin-bottom: 10px; padding: 2px; border: 1px solid #ccc;" src="http://www.gen-x-design.com/wp-content/uploads/2009/06/phpthumb.png" alt="PHP Thumb - An image manipulation library for PHP" title="PHP Thumb - An image manipulation library for PHP"width="580" height="120" /></div>
<p>Well, it&#8217;s been a long time coming, but I&#8217;ve finally managed to get the next release of my PHP Thumbnailer library completed!  I&#8217;m also happy to announce that the project finally has its own website: <a href="http://phpthumb.gxdlabs.com">http://phpthumb.gxdlabs.com</a>.  I&#8217;ve put a lot of work into bringing the class up to date, making it extensible, and most of all, making sure its well documented!  I&#8217;ve also tried to make it easier to get help through either bug reports or forums dedicated to the project itself.</p>
<p>Rather than go into any detail, I want to encourage you to check out the project&#8217;s new site.  Feel free, however, to share any thoughts you have in the comments for this post <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/php-thumb-30-released/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Web Developer Collection: Packaged up Firefox extensions</title>
		<link>http://www.gen-x-design.com/archives/web-developer-collection-packaged-up-firefox-extensions/</link>
		<comments>http://www.gen-x-design.com/archives/web-developer-collection-packaged-up-firefox-extensions/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 18:14:34 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Asides]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[firefox]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=304</guid>
		<description><![CDATA[
Mozilla announced a new feature for add-ons today: collections.  It also looks like they&#8217;re getting the ball rolling with several useful collections, such as the Web Developer Collection.  It includes all sorts of goodness like Firebug, ySlow, GreaseMonkey, ColorZilla, and many more.  Well worth a quick visit.
FireFox Web Developer Collection
]]></description>
			<content:encoded><![CDATA[<div style="margin-bottom: 10px; text-align: center;" class="sidebar-image"><a href="https://addons.mozilla.org/en-US/firefox/collection/webdeveloper" target="_blank"><img src="http://www.gen-x-design.com/wp-content/uploads/2009/06/mozilla-addons.png" alt="Mozilla Add-ons" style="padding: 2px; border: 1px solid #ccc;" width="260" height="50" /></a></div>
<p>Mozilla announced a new feature for add-ons today: collections.  It also looks like they&#8217;re getting the ball rolling with several useful collections, such as the Web Developer Collection.  It includes all sorts of goodness like Firebug, ySlow, GreaseMonkey, ColorZilla, and many more.  Well worth a quick visit.<br />
<a href="https://addons.mozilla.org/en-US/firefox/collection/webdeveloper" target="_blank">FireFox Web Developer Collection</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/web-developer-collection-packaged-up-firefox-extensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MooTools ScrollSpy &#8211; Surprising Useful JS Plugin</title>
		<link>http://www.gen-x-design.com/archives/mootools-scrollspy-surprising-useful-js-plugin/</link>
		<comments>http://www.gen-x-design.com/archives/mootools-scrollspy-surprising-useful-js-plugin/#comments</comments>
		<pubDate>Fri, 29 May 2009 21:20:51 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Asides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MooTools]]></category>
		<category><![CDATA[ScrollSpy]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=299</guid>
		<description><![CDATA[
David Walsh has put together a really handy plugin for MooTools called ScrollSpy.  What impressed me the most was the automatic display of a &#8220;Return to Top&#8221; link on your page once you&#8217;ve scrolled beyond a certain boundary.  There are also a handful of other neat demos worth checking out.  Sounds simple, [...]]]></description>
			<content:encoded><![CDATA[<div style="margin-bottom: 10px; text-align: center;" class="sidebar-image"><a href="http://davidwalsh.name/scrollspy" target="_blank"><img src="http://www.gen-x-design.com/wp-content/uploads/2009/05/img-scrollspy.png" style="padding: 2px; border: 1px solid #ccc;" width="260" height="50" /></a></div>
<p>David Walsh has put together a really handy plugin for MooTools called ScrollSpy.  What impressed me the most was the automatic display of a &#8220;Return to Top&#8221; link on your page once you&#8217;ve scrolled beyond a certain boundary.  There are also a handful of other neat demos worth checking out.  Sounds simple, but if you think about it, there are tons of great applications for this plugin.<br />
<a href="http://davidwalsh.name/scrollspy" target="_blank">http://davidwalsh.name/scrollspy</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/mootools-scrollspy-surprising-useful-js-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery vs. MooTools &#8211; Finally, a Useful &amp; Subjective JS Framework Comparison</title>
		<link>http://www.gen-x-design.com/archives/jquery-vs-mootools/</link>
		<comments>http://www.gen-x-design.com/archives/jquery-vs-mootools/#comments</comments>
		<pubDate>Thu, 21 May 2009 18:00:03 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Asides]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MooTools]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=292</guid>
		<description><![CDATA[
It&#8217;s been said a thousand times I&#8217;m sure, but picking the right JavaScript framework is a pain.  There are all sorts of biased arguments for one vs. another, but there&#8217;s really nothing subjective out there&#8230; until now.  Arguably, jQuery is probably the most popular JS framework out in the wild, but that doesn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<div style="margin-bottom: 10px; text-align: center;" class="sidebar-image"><a href="http://jqueryvsmootools.com/" target="_blank"><img src="http://www.gen-x-design.com/wp-content/uploads/2009/05/jquery_vs_mootools.png" style="padding: 2px; border: 1px solid #ccc;" width="260" height="50" /></a></div>
<p>It&#8217;s been said a thousand times I&#8217;m sure, but picking the right JavaScript framework is a pain.  There are all sorts of biased arguments for one vs. another, but there&#8217;s really nothing subjective out there&#8230; until now.  Arguably, jQuery is probably the most popular JS framework out in the wild, but that doesn&#8217;t always mean it&#8217;s the best choice.  What you choose should really depend on what you&#8217;re trying to do.  Aaron Newton of Clientcide has put together a really impressive look at jQuery vs. MooTools, which doesn&#8217;t categorically say one is better than the other, but, rather, goes into detail about why one framework is better than the other based on your needs.  Definitely worth a read:<br />
<a href="http://www.jqueryvsmootools.com/" target="_blank">www.jqueryvsmootools.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/jquery-vs-mootools/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Doctrine &#8211; PHP Object Relational Mapper</title>
		<link>http://www.gen-x-design.com/archives/doctrine-php-object-relational-mapper/</link>
		<comments>http://www.gen-x-design.com/archives/doctrine-php-object-relational-mapper/#comments</comments>
		<pubDate>Wed, 20 May 2009 20:59:28 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Asides]]></category>
		<category><![CDATA[Doctrine]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=288</guid>
		<description><![CDATA[
ORM is certainly a very popular concept these days, but I haven&#8217;t really come across any PHP implementations that I found worth-while.  Sure, big frameworks like CakePHP may have ORM functionality, but I&#8217;m not a fan of huge frameworks.  I&#8217;ve also dabbled in my own implementations, but never got too far, as I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<div style="margin-bottom: 10px; text-align: center;" class="sidebar-image"><a href="http://www.doctrine-project.org/" target="_blank"><img src="http://www.gen-x-design.com/wp-content/uploads/2009/05/img_doctrine.png" style="padding: 2px; border: 1px solid #ccc;" width="260" height="50" /></a></div>
<p>ORM is certainly a very popular concept these days, but I haven&#8217;t really come across any PHP implementations that I found worth-while.  Sure, big frameworks like CakePHP may have ORM functionality, but I&#8217;m not a fan of huge frameworks.  I&#8217;ve also dabbled in my own implementations, but never got too far, as I&#8217;m not a fan of re-inventing the wheel.  At any rate, I stumbled across Doctrine by accident (good ol&#8217; RSS readers), and am impressed,  mostly because it&#8217;s something that can be integrated into existing projects / frameworks.<br />
<a href="http://www.doctrine-project.org/" target="_blank">www.doctrine-project.org</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/doctrine-php-object-relational-mapper/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Making RESTful Requests in PHP</title>
		<link>http://www.gen-x-design.com/archives/making-restful-requests-in-php/</link>
		<comments>http://www.gen-x-design.com/archives/making-restful-requests-in-php/#comments</comments>
		<pubDate>Thu, 14 May 2009 19:47:03 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Off Topic]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[DELETE]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[PUT]]></category>
		<category><![CDATA[Request]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.gen-x-design.com/?p=269</guid>
		<description><![CDATA[APIs have become a very commonplace part of many popular web sites and services&#8230; especially REST APIs.  I&#8217;ve already discussed how you can roll your own REST API for your PHP apps, but I&#8217;ve also received countless requests to go over how to actually make RESTful requests.  That&#8217;s exactly what we&#8217;ll take a [...]]]></description>
			<content:encoded><![CDATA[<p>APIs have become a very commonplace part of many popular web sites and services&#8230; especially REST APIs.  I&#8217;ve already <a href="http://www.gen-x-design.com/archives/create-a-rest-api-with-php/">discussed</a> how you can roll your own REST API for your PHP apps, but I&#8217;ve also received countless requests to go over how to actually make RESTful requests.  That&#8217;s exactly what we&#8217;ll take a look at in this article.  Before we dive in, however, I want to make sure you&#8217;ve got a basic understanding of how REST APIs work, so if you&#8217;re a bit shaky or unfamiliar with the concept, head on over to my <a href="http://www.gen-x-design.com/archives/create-a-rest-api-with-php/">previous article on REST</a> and read up (you don&#8217;t need to go over the implementation stuff if you don&#8217;t want, just read the first part of the article).  Seriously, do it&#8230; this article is written with the assumption you&#8217;re familiar with the concepts of REST.</p>
<p>Anyway, without any further delay, let&#8217;s take a look at what we&#8217;re going to cover&#8230;<br />
<span id="more-269"></span></p>
<h2>The Basics of a RESTful Request</h2>
<p>Every REST request consists of essentially the same basic parts:</p>
<ul>
<li><strong>The URL</strong> &#8211; This is the URL we&#8217;ll be making a request against (often referred to as a resource).</li>
<li><strong>The Verb</strong> &#8211; GET, POST, PUT, or DELETE&#8230; there are some others out there, but these are the 4 most common ones.</li>
<li><strong>The Params</strong> &#8211; The parameters we&#8217;ll be supplying to the API, often referred to as the request body.</li>
<li><strong>Credentials</strong> &#8211; Username and password&#8230; we&#8217;ll cover HTTP Digest auth credentials.</li>
</ul>
<p>And, of course, we&#8217;ll have a few pieces for our response as well:</p>
<ul>
<li><strong>The Response Body</strong> &#8211; The actual response body the API gave us.</li>
<li><strong>The Response Status Code</strong> &#8211; The HTTP status code the API responded with.</li>
<li><strong>Other Response Info</strong> &#8211; We&#8217;ll also have some other interesting info in the response.</li>
</ul>
<p>Nothing really unexpected here, everything&#8217;s probably looking like what you&#8217;d expect: a request and a response.</p>
<p>So, on to the answer to the most important question: &#8220;How the heck do you actually make the request?!?!?&#8221;</p>
<h2>REST &amp; PHP &#8211; Curl to the Rescue</h2>
<p>You may have already guessed we&#8217;d be using curl (or suspected it perhaps)&#8230; and if you didn&#8217;t, well, that&#8217;s what we&#8217;ll be using <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Anyway, if you&#8217;ve ever worked with Curl in PHP, you&#8217;re probably aware that making GET and POST requests are pretty straight-forward, but the PUT and DELETE requests are a little less obvious.  Luckily, they&#8217;re pretty easy once you know how to do them, the problem is that they&#8217;re very poorly documented.  We&#8217;ll go over them soon, but let&#8217;s get started with a little code.  We&#8217;re going to be building a class that we can use to make requests and deal with their responses, so why don&#8217;t we build up a bit of a base class, and then start filling things in:</p>
<pre name="code" class="php">
class RestRequest
{
	protected $url;
	protected $verb;
	protected $requestBody;
	protected $requestLength;
	protected $username;
	protected $password;
	protected $acceptType;
	protected $responseBody;
	protected $responseInfo;

	public function __construct ($url = null, $verb = 'GET', $requestBody = null)
	{
		$this->url				= $url;
		$this->verb				= $verb;
		$this->requestBody		= $requestBody;
		$this->requestLength		= 0;
		$this->username			= null;
		$this->password			= null;
		$this->acceptType		= 'application/json';
		$this->responseBody		= null;
		$this->responseInfo		= null;

		if ($this->requestBody !== null)
		{
			$this->buildPostBody();
		}
	}

	public function flush ()
	{
		$this->requestBody		= null;
		$this->requestLength		= 0;
		$this->verb				= 'GET';
		$this->responseBody		= null;
		$this->responseInfo		= null;
	}

	public function execute ()
	{

	}

	public function buildPostBody ($data = null)
	{

	}

	protected function executeGet ($ch)
	{		

	}

	protected function executePost ($ch)
	{

	}

	protected function executePut ($ch)
	{

	}

	protected function executeDelete ($ch)
	{

	}

	protected function doExecute (&#038;$curlHandle)
	{

	}

	protected function setCurlOpts (&#038;$curlHandle)
	{

	}

	protected function setAuth (&#038;$curlHandle)
	{

	}
}
</pre>
<p>So, what we&#8217;ve got here is essentially all of the functions we&#8217;ll need to make this whole thing work right.  We&#8217;ll cover each of the function individually, but let&#8217;s take a look at the class members:</p>
<ul>
<li><strong>$url</strong> &#8211; The URL we&#8217;ll be requesting against</li>
<li><strong>$verb</strong> &#8211; The type of request we&#8217;ll be making (what verb to use)</li>
<li><strong>$requestBody</strong> &#8211; The request body we&#8217;ll send with PUT and POST requests</li>
<li><strong>$requestLength</strong> &#8211; An internally used variable for PUT requests (more on this later)</li>
<li><strong>$username</strong> &#8211; The username to use for this request</li>
<li><strong>$password</strong> &#8211; I&#8217;ll let you guess <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </li>
<li><strong>$acceptType</strong> &#8211; What kind of content we&#8217;ll accept as a response (not all APIs use this to determine the response format, but we&#8217;ll be robust)</li>
<li><strong>$responseBody</strong> &#8211; The body of our response</li>
<li><strong>$responseInfo</strong> &#8211; All the other goodness from our response (status code, etc.)</li>
</ul>
<p>Not too rough, right?  And if you take a look at the constructor, you&#8217;ll see things are pretty straight-forward as well.  We&#8217;ve also got a flush function.  This allows us to use the same object to make multiple requests by only clearing out certain member variables (notice username / password aren&#8217;t touched).  You may have also noticed we&#8217;re missing getters / setters&#8230; this is simply to keep the code a little shorter.  The final class will have them.</p>
<h2>Making Requests &#8211; The Prep Work</h2>
<p>Let&#8217;s go ahead and fill in some of the functions that do prep work for us, and then we&#8217;ll dig into making the requests.  Anyway, let&#8217;s take a look at these &#8220;init&#8221; functions..</p>
<p><strong>buildPostBody</strong><br />
This function will take an array and prepare it for being posted (or put as well):</p>
<pre name="code" class="php">
	public function buildPostBody ($data = null)
	{
		$data = ($data !== null) ? $data : $this->requestBody;

		if (!is_array($data))
		{
			throw new InvalidArgumentException('Invalid data input for postBody.  Array expected');
		}

		$data = http_build_query($data, '', '&#038;');
		$this->requestBody = $data;
	}
</pre>
<p>Notice how we will throw exceptions if we receive anything other than an array?  This is important, as we don&#8217;t want our data to be malformed (or an error to be thrown by http_build_query).  Also, you may be thinking that I&#8217;m using an exception type that isn&#8217;t defined anywhere&#8230; well, it is (if you&#8217;re using PHP 5).  I won&#8217;t go off on a tangent, but check out the <a href="http://php.net/spl" target="_blank">PHP SPL</a> for more info.  All you need to know is that the InvalidArgumentException is already defined for you <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>setCurlOpts</strong><br />
This function will take care of all the curl options common to all our requests:</p>
<pre name="code" class="php">
	protected function setCurlOpts (&#038;$curlHandle)
	{
		curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10);
		curl_setopt($curlHandle, CURLOPT_URL, $this->url);
		curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType));
	}
</pre>
<p><strong>setAuth</strong><br />
If we&#8217;ve got a username and password set on the class, we&#8217;ll set up the auth options on the curl request with this function:</p>
<pre name="code" class="php">
	protected function setAuth (&#038;$curlHandle)
	{
		if ($this->username !== null &#038;&#038; $this->password !== null)
		{
			curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
			curl_setopt($curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password);
		}
	}
</pre>
<p>I mentioned earlier that we&#8217;re only going to cover HTTP Digest authentication in this class, but you could adapt this function to suit your needs however you wanted depending on what the API(s) you&#8217;re consuming require.</p>
<h2>Making the REST Requests</h2>
<p>We&#8217;re about ready to cover how to make the individual verb requests, but we need to do just a little bit more work filling in the common functionality.  We&#8217;ll go ahead and create our doExecute and execute functions now:</p>
<pre name="code" class="php">
	public function execute ()
	{
		$ch = curl_init();
		$this->setAuth($ch);

		try
		{
			switch (strtoupper($this->verb))
			{
				case 'GET':
					$this->executeGet($ch);
					break;
				case 'POST':
					$this->executePost($ch);
					break;
				case 'PUT':
					$this->executePut($ch);
					break;
				case 'DELETE':
					$this->executeDelete($ch);
					break;
				default:
					throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.');
			}
		}
		catch (InvalidArgumentException $e)
		{
			curl_close($ch);
			throw $e;
		}
		catch (Exception $e)
		{
			curl_close($ch);
			throw $e;
		}

	}

	protected function doExecute (&#038;$curlHandle)
	{
		$this->setCurlOpts($curlHandle);
		$this->responseBody = curl_exec($curlHandle);
		$this->responseInfo	= curl_getinfo($curlHandle);

		curl_close($curlHandle);
	}
</pre>
<p>Looks like a lot of code, but it&#8217;s actually pretty simple stuff.  </p>
<p>First, looking at execute, you&#8217;ll see that we set up a curl handle variable ($ch), and then run the setAuth function.  Since we pass $ch around by reference, the functions will directly manipulate the variable without any need to return it.  Now, I could make the $ch a member variable, but for the sake of this example, I wanted to show how everything gets passed around a little more explicitly.  Anyway, the next thing we do is normalize the verb, and run through our switch statement to determine what function will get executed.  If we don&#8217;t find a matching case, we throw an exception.  We also wrap the whole thing in a try / catch block so we can properly catch exceptions, close our curl handle, then throw the exception again (presumably for some other error handler or try / catch block elsewhere in the code).</p>
<p>Moving on to the doExecute function, you&#8217;ll see all we really do here is set all the common curl options with setCurlOpts, execute the request, and get the response body and info.  We&#8217;ll take a look at those in a bit, but let&#8217;s get to the individual request functions.</p>
<h2>GET Requests</h2>
<p>These requests are about as easy as they get.  Since your params will be a part of the URL, there isn&#8217;t much to do outside of actually making the request.  So our code is nice and easy:</p>
<pre name="code" class="php">
	protected function executeGet ($ch)
	{
		$this->doExecute($ch);
	}
</pre>
<p>&#8216;Nuff said <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>POST Requests</h2>
<p>These too are pretty easy to accomplish, and POSTing with Curl is well-documented.  Nonetheless, here&#8217;s what our function looks like:</p>
<pre name="code" class="php">
	protected function executePost ($ch)
	{
		if (!is_string($this->requestBody))
		{
			$this->buildPostBody();
		}

		curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
		curl_setopt($ch, CURLOPT_POST, 1);

		$this->doExecute($ch);
	}
</pre>
<p>All we really do here is make sure the request body is a string, and if it isn&#8217;t that means we need to prepare it&#8230; so we do.  Then we tell Curl to make a POST request with the provided POST body.  That&#8217;s all there is to it!  Moving on&#8230;</p>
<h2>PUT Requests in PHP</h2>
<p>Ah, PUT requests&#8230;  These are the big mystery.  Admittedly, there are a few articles out there covering how to do them, but they&#8217;re not super-easy to come across.  I did, however, manage to find a few and here&#8217;s what I came up with:</p>
<pre name="code" class="php">
	protected function executePut ($ch)
	{
		if (!is_string($this->requestBody))
		{
			$this->buildPostBody();
		}

		$this->requestLength = strlen($this->requestBody);

		$fh = fopen('php://memory', 'rw');
		fwrite($fh, $this->requestBody);
		rewind($fh);

		curl_setopt($ch, CURLOPT_INFILE, $fh);
		curl_setopt($ch, CURLOPT_INFILESIZE, $this->requestLength);
		curl_setopt($ch, CURLOPT_PUT, true);

		$this->doExecute($ch);

		fclose($fh);
	}
</pre>
<p>A little funky, right?  Well, this boils down to the way PUT requests are technically supposed to work.  RESTful APIs don&#8217;t quite use a PUT the way they were originally intended, which is for file uploads.  As such, we need to stream the data to the web server.  So we open an internal php memory resource, write our request body to it, and then pass the handle for that memory resource to curl.  We also calculate the size of it (in bytes), so that our full body will be received on the API side of things.  I suppose that doesn&#8217;t necessarily need to make any sense to you, as long as you trust that it works <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h2>DELETE Requests in PHP</h2>
<p>Deletes, when done as they&#8217;re intended (no post body), are easy.  Remember, you&#8217;re not really supposed to send any body for a delete request, as you&#8217;re merely sending a command to a resource (i.e. /api/user/1).  Here&#8217;s the code:</p>
<pre name="code" class="php">
	protected function executeDelete ($ch)
	{
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

		$this->doExecute($ch);
	}
</pre>
<p>Now, if you need to send a body for some reason, you can do it by adding the same stuff you use for a PUT request, but swap out the CURLOPT_PUT line for the existing CURLOPT_CUSTOMREQUEST line that we&#8217;ve got in this function.  I don&#8217;t advocate this, but it works like a champ if you need it.</p>
<h2>The Response</h2>
<p>Now that we&#8217;ve got a fully functioning REST requester, let&#8217;s take a look at a response.  So, making a request against an imaginary API looks something like:</p>
<pre name="code" class="php">
$request = new RestRequest('http://example.com/api/user/1', 'GET');
$request->execute();

echo '&lt;pre&gt;' . print_r($request, true) . '&lt;/pre&gt;';
</pre>
<p>Which gives us output similar to:</p>
<pre name="code">
RestRequest Object
(
    [url:protected] => http://example.com/api/user/1
    [verb:protected] => GET
    [requestBody:protected] =>
    [requestLength:protected] => 0
    [username:protected] =>
    [password:protected] =>
    [acceptType:protected] => application/json
    [responseBody:protected] => [RESPONSE BODY HERE]
    [responseInfo:protected] => Array
        (
            [url] => http://example.com/api/user/1
            [content_type] => application/json
            [http_code] => 200
            [header_size] => 232
            [request_size] => 192
            [filetime] => -1
            [ssl_verify_result] => 0
            [redirect_count] => 0
            [total_time] => 0.015693
            [namelookup_time] => 0.0004
            [connect_time] => 0.000571
            [pretransfer_time] => 0.000619
            [size_upload] => 0
            [size_download] => 4276
            [speed_download] => 272478
            [speed_upload] => 0
            [download_content_length] => 4276
            [upload_content_length] => 0
            [starttransfer_time] => 0.015655
            [redirect_time] => 0
        )
)
</pre>
<p>Take a look at the responseInfo&#8230; we&#8217;ve got our status code, and all sorts of other good stuff.  And, believe it or not, we&#8217;re done!</p>
<h2>Wrapping Up</h2>
<p>Of course, as with all my samples, there&#8217;s a lot left for you to do.  You&#8217;ll probably want to do some processing of the response body and info (such as extracting the status code), or make a few things more robust, but this is all you should need to get started.  Hopefully, after this article and the previous one, you&#8217;ve got a good idea of how REST APIs work from the server-side, to the client-side, and you&#8217;re ready to jump on the REST bandwagon.  If you&#8217;re not yet convinced&#8230; go play with some SOAP APIs, that ought to change your mind <img src='http://www.gen-x-design.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Finally, you can grab the final copy of the class, complete with getters / setters at the link below:<br />
<a href='http://www.gen-x-design.com/wp-content/uploads/2009/05/restrequestincphp1.zip'>RestRequest.inc.php &#8211; Final Source Code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gen-x-design.com/archives/making-restful-requests-in-php/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
	</channel>
</rss>
