2011-12-25

PHP Fog Quickstart

For a while, I've been trying to find a good hosting service to use for testing out PHP apps and ideas I have. My criteria was to find a service that would be like Heroku for PHP apps: simple to get started, pre-configured with access to a database, scalable on demand, and no-hassle deployment (able to integrate with continuous deployment.)

Funnily enough, if you do a Google search for "heroku php" the first thing that comes up is PHP Fog. They provide hosting for up to 3 projects for free on shared hosting. They also offer MongoDB and application monitoring as add-ons.

Being it was Christmas and all, I decided to give myself a present and sign up. I was very surprised by how easy it was to get up and running. I managed to build a simple "echo" service in about 8 minutes, following roughly these steps:

After logging in, click "Launch New App". This brings you to a screen where you can choose from several pre-built applications (popular CMS or blogging platforms) or skeleton projects built on the most popular PHP frameworks.

For my purposes, I chose "Custom App". This will build an application containing exactly one "Hello world" PHP file. Enter a password for the MySQL database that will be set up, and a subdomain. The subdomain must be unique among all PHP Fog apps, and the setup won't continue until it is. After your app is set up, it can be given a custom domain name from $5 per month.

Click "Create App". This will bring you to your project's management page. From here, you can find everything you need to start developing your app. The git repository address for the app is displayed, as are the database credentials, helpfully wrapped in a mysql_connect function call.

Eventually, the "Status" light will turn green, indicating that your app is available. Clicking "View Live Site" brings you to your application, live to the world. Not much there. Time to change that.

Follow the instructions to add an SSH key to PHP Fog, which will give you access to write to your application's git repo. Then use the given git address to clone the repo to your development environment. Also, grab the Silex microframework to start building the app:
> git clone git@git01.phpfog.com:myapp.phpfogapp
> cd myapp.phpfogapp
> wget http://silex.sensiolabs.org/get/silex.phar
Edit index.php to provide a simple endpoint which will greet users:
<?php
require_once __DIR__.'/silex.phar';

$app = new Silex\Application();

$app->get('/', function() use($app) {
    return 'Checkout <a href="/hello/world">Hello...</a>';
});

$app->get('/hello/{name}', function($name) use($app) {
    return 'Hello '.$app->escape($name);
});

$app->run();
Also, create an .htaccess file that will redirect all traffic to index.php:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Add the files to repository, commit them, then push the master branch to make the changes live:
> git add index.php .htaccess silex.phar
> git commit
> git push origin master
Reload your site to see the changes. Follow the "Hello" link, and play with the URL to see the results.

After the holidays, I hope to actually build something interesting on the platform.

2011-12-17

Decode JSON in Bash with PHP

I recently found myself needing to make cUrl calls from the command-line to an endpoint which returned JSON responses. Rather than parsing through the JSON as a string, or downloading some third party tool to format it for me, I created this handy Bash alias that decodes JSON from the command-line using PHP.

Put the following in your ~/.bashrc file:
alias json-decode="php -r 'print_r(json_decode(file_get_contents(\"php://stdin\")));'"

Usage from any process:
echo '{"foo":"bar","baz":"qux"}' | json-decode

Or from a cUrl call:
curl -s http://example.com/json/endpoint | json-decode

2011-12-08

Codeworks '11 Raleigh Rundown

I had a great time at CodeWorks 2011 in Raleigh this week, put on by the great folks at php|architect. Here is a rundown of the presentations, with some of my thoughts.

CI:IRL

Beth Tucker Long started out the day with a talk about continuous integration tools for automating away the pain of building and deploying PHP projects. One of her main themes was the importance of standardization in your code to avoid wasting mental effort on things like variable and class naming, which lines to put curly braces on, or how many spaces are in a single indent (editor: the answer is none; use a tab character.) The same can be said about manual testing and deployment processes.

The tools discussed included PHP_CodeSniffer, the venerable and nigh ubiquitous PHPUnit, and multiple options for automated builds and testing (CruiseControl and Jenkins/Hudson.) Beth also talked about Phing, which is one of my new favorite tools. She also covered tools for automated documentation and report generation. I would have gone with DocBlox instead of phpDocumentor, but that's just a personal preference. The most useful thing about most of these tools is that many of them are aware of each other, directly or through plugins, and can be chained together to build a flexible CI pipeline.

Most of the tools I had already heard of or am actively using. In addition to PHP_CodeSniffer for coding standards compliance, I would also throw in one or both of PHP Mess Detector and PHP Copy-Paste Detector. These three tools together give great insights into the current state of your code base and its future maintainability, which Beth mentioned when discussing "technical debt".

An important thing that Beth stressed at the end of her presentation was that not every project requires the use of every tool. It's important to take into account things like size/complexity of the project, timeline, budgets and team size. I think this was a valuable piece of advice that a lot of people forget. If you're anything like me, when you first learn about a new tool your response is to go out and find as many ways to use it as possible. I'm glad Beth ended with the reminder to keep in mind the constraints of your project when picking which tools to apply.

How Beer Made Me A Better Developer

Next up was Jason Austin, who is one of the coordinators of my local PHP meetup group. Jason's talk was a call for all developers to find their passion. His two passions are beer and PHP, so he decided to combine them into a side project, and Pint Labs was born. All developers should find a side project related to their passion. It is something he looks for as a hiring manager. They also prevent burnout in your day job.

Side projects give developers an opportunity to experiment without the consequences of failure that usually accompany employed or contract work. More than that, they allow for greater opportunities to bring new knowledge to a paid job. "The dumbest thing a manager can do is stop their developers from working on their own side projects," was one of my favorite lines from the presentation.

I can't agree more, and I'm lucky to have never worked in an environment where an employer has either forbidden me from having side projects, or claimed that anything I work on in my own time belongs to the company. I learned at lunch that many people aren't so fortunate. I would be very wary of any employment where that was the case.

As for side projects, even if you don't start your own, there are tons of open source projects out there who would love more hands on keyboards helping out. There is no excuse for not getting involved, even at a small degree.

What's New in PHP 5.4

Of all the talks, Cal Evans's about the new features coming in PHP 5.4 was probably the least applicable to my current work, but was one of my favorites. Cal is an engaging speaker, and there is some really cool stuff coming up in PHP.

The bits I was most interested in were improvements in Closures, Traits, and the built-in HTTP server. For those who don't know, in PHP 5.4, closures created in an object method will be able to reference $this from within the closure. That may not seem like a big deal, but if you're working with classes that build themselves or are factories for other objects, having the ability to reference the creating object is incredibly useful. The closure can access protected and private stuff from the instantiated class.

The caveat is that $this will always reference the object in which the closure was created. It would be great to be able to bind $this to whatever object was invoking the closure, like you can with Javascript's .call() and .apply() functions.

Lots has been written about Traits. Of all the features in PHP 5.4, this is the one I'm most looking forward to. They will solve a lot of problems that currently can only be solved by having deeply nested class hierarchies. Combining traits with the ability to bind closures to an object paves the way for having completely dynamically created classes, which would be useful in many situations. It also gives more evidence for my theory that every programming language evolves until it can replicate Javascript.

One other thing that Cal mentioned was the new JsonSerializable interface. This is a great addition for anyone who deals with sending JSON responses in PHP. I only have one problem with it: there is no complementary JsonUnserializable interface that would allow an object to populate its properties from a JSON string. I don't watch the PHP internals list, so I don't know why it was decided not to include such obvious functionality. Does anyone have any insights?

Refactoring and Other Small Animals

After lunch, we got right into the second half of the day with Marco Tabini and a presentation on refactoring. The presentation centered around a piece of "legacy" code. He wrote a test to assert the existing behavior, then proceeded to follow the refactoring steps of abstract, break (apart) and rename to show how the code could be made more maintainable and testable.

Marco's talk was to the point, with a great example, but it tilted more towards the theoretical side of why you should refactor. It also took a very purist look at what refactoring means (absolutely no changes to interface, even changes that would not affect calling code.) While I agree that this is the technical definition of refactoring, it's hard to start poking at a piece of code without wanting to improve its usage instead of just its implementation. I think there is a fuzzy line that developers cross often, at least mentally, between refactoring and improving the interface.

At the after-party, some of my coworkers had a longer discussion with Marco where he expounded on some of the ideas he presented and gave some more practical advice for our own legacy application. I wasn't there, but I do appreciate speakers and experts taking the time to apply their own knowledge and experience to their audience's issues. So, thank you Marco.

Jquery Mobile and PhoneGap

Terry Ryan was the representative from Adobe, one of the conference sponsors. His talk began with a quick demo of building an app with jQuery Mobile. I'll admit, I'm not a big fan of doing UI or front-end development, but even I could see how working with a library like that could make such development fun. It seems some of the kinks still need to be worked out, but it looks like a promising library and I hope to play with it some day soon.

Following that was an overview of PhoneGap, and more impressively, PhoneGap:Build, where Terry tweaked his application, ran it through the cloud building service, and had the new app deployed to his phone in just a few minutes, all live. Impressive stuff!

Then, Terry showed off some of the things Adobe has in the works with CSS shaders. The effects he demoed were neat to look at, but I don't feel like there was anything there that WebGL doesn't already cover.

For a finale, Terry live demoed Adobe's Proto application, which allows tablet users to create UI wireframes and mock-ups by drawing with their fingers. Imagine a virtual whiteboard that takes your scratchings and turns them into divs, tables, text, headers and image frames live while you draw. Now imagine sharing that view with remote users, also live. Very cool stuff.

REST Best Practices

Keith Casey's presentation was an informative look into the philosophy and reasoning behind REST architecture, and was another one of my favorites. He talked about the myth of "strictly RESTful" and how the vast majority of APIs out there don't even come close (hint #1: if you're passing an authentication token or session ID on every request, your API is not RESTful.) I also liked his use of "-ilities": discoverability, readability, flexibility, maintainability, etc.

He used Twilio as his example API, and showed how a good REST API should follow the 6 constraints of REST: client-server, stateless (where most authentication schemes fail at being REST), cacheable, layered, uniform interface, and code-on-demand. The last constraint is the hardest one for me to get my head around, so I appreciated his use of GMail as an example of providing not just data, but the code that manipulates that data. I think that JSONP might also fall into that category, but I didn't get a chance to ask.

Like with Marco's talk, I appreciated the theoretical nature of the topic, but I would have liked some more examples of real-world practicality trumping academic purity. It's always nice when a speaker acknowledges that sometimes you just need to get things done and points out which portions of a technology are more flexible than others and amenable to not following the letter of the law. Besides that, I thought it was a great look into why REST is the way it is.

After-Party

No development conference is complete without an after-party and no after-party is complete without free beer. I'd like to thank the folks at SugarCRM for sponsoring the after-party at Tir na nOg, one of my favorite pubs in downtown Raleigh.

Besides free booze, I love to talk with speakers and other conference attendees in a less formal setting. It's great to get to know other developers at the top of their craft, and the people in the PHP community are some of the friendliest and easiest going. It's one of the reasons I love being a PHP developer so much. Keith, his coworker at Twilio Devin Rader, a few other people and I had a great conversation that shifted topics basically at the speed of thought. John Mertic from SugarCRM was there and answered some of my questions, and Beth explained the php|architect submission process in a way that didn't sound scary at all.

To all the conference speakers, organizers and attendees, I want to say thank you for a fun and educational experience. Hopefully some of us will meet up again at phptek 2012!