Archive for the ‘PHP’ Category

Symfony2: JSON responses for XHR errors and authentication failures

I’ve been working on a Symfony2 application whose user interface is presented as a single page application that makes heavy use of JavaScript. The app sends XHR requests to the Symfony2 backend API to retrieve and modify data, and it uses Symfony’s authorisation/authentication functionality to protect resources so they are only accessible to logged in users.

In an ideal world every request made by the application will succeed, but in reality things often go wrong; the user may have provided invalid data, their session may have expired meaning they are no longer logged in, or we may have a bug in our API code which causes a server error. With an out-of-the-box installation of Symfony2, each of these scenarios will result in the default error handler rendering a HTML page which isn’t much use to our client JavaScript application – instead we want the server to issue a JSON response to our AJAX request, complete with some contextual error details, with which we can give the user a meaningful error message.

I did a bit of Googling and came across a few posts which dealt with some of these challenges, and by putting them all together I arrived at a solution which I’ll detail here in case it’s of use to anyone else.

I’ve put together a demo app which hopefully illustrates everything. Have a play with it (installation instructions are in the README), then read on :)

The app consists of a few components:

Client side:

  • A jQuery global AJAX error handler
  • A login form – I have two, a Symfony2/Twig-based HTML login page which the user is redirected to if they try to access the app without a valid session, and a JavaScript login dialog which we will display if the server rejects an AJAX request due to authentication/authorisation failure, allowing the user to reauthenticate without leaving the app

Server side:

  • An authentication failure handler
  • An authentication success handler
  • A kernel exception listener

As far as the rest of the app goes, I’m using the FOSUserBundle with a standard configuration, which supplies the rest of the auth functionality, including the HTML login page.

Let’s start with the server components – three classes and a bit of config:

The XHRAuthenticationSuccessHandler and XHRAuthenticationFailureHandler class’ code is triggered when the user logs in, or fails to log in, respectively. We check to see if the original request was an AJAX (XHR) one, and if so we respond with JSON. If it’s a failure we’re dealing with, we also include the exception message to give the user some feedback – note that this is a quick solution; it might be prudent to vet the message, or to translate it. I’ve also included a ‘success’ property which is a JavaScript convention that some frameworks (like ExtJS) use to execute appropriate callbacks. Finally, we wire up these handlers with the security component in our application’s security configuration.

The XHRCoreExceptionListener class code is triggered whenever a kernel exception occurs – check the service definition for this listener, you’ll see we tell Symfony to call its onCoreException method whenever an exception event is fired. Again, we only want to act if the request that caused the exception was an AJAX one. Assuming it is, we try to work out the status code to return from the exception code – if it’s a valid HTTP code, we use that, otherwise we assume a server error (500). As before, we’re reusing the exception message to provide context – but in this case, where the exception could relate to anything in the system (like a database query) we’d really want to be cautious about exposing it to the user, so this code certainly isn’t suitable for a production environment.

That’s it for the server, now for the client. All the functionality is in src/Acme/DemoBundle/Resources/views/Welcome/index.html.js.

First we define a global error handler, which will be fired whenever an uncaught AJAX error occurs:

If the problem is that the user does not have a valid authentication token, we invite them to log in.

The login process is interesting – the modal login form is essentially a duplicate of the HTML one, but lacks the CSRF token which is automatically injected into the HTML form by Symfony. This helps prevent spoofing so I didn’t want to remove it, so the approach I took was to request the HTML login page, capture the value of the CSRF field in the response, then use that in a second request to actually authenticate the user. This meant I could reuse the same authentication code on the server.

The demo app also includes two other demonstrations – making a valid request (which will fail, and force a login, if the user does not have a valid session) and an invalid one (which displays the error message returned by the server). There’s not much to say about those, the code should be self explanatory.

That’s it really. The code is a little rough and ready, but hopefully it’ll give you enough to go on if you’re trying to do something similar!

Symfony2: Managing a User entity role with a Form Event Subscriber

I’m working on a Symfony2 application which makes use of roles to manage what Users of the system are able to do within the app. Symfony places no limit on the amount of roles the User can have, but in the context of my application, there are only two – a base user (ROLE_USER, in Symfony parlance), and an administrator (ROLE_ADMIN). As is Symfony custom, all users would possess the default role, but the administrator role would be granted on a per user basis. I’m using the FOSUserBundle and Doctrine, so a User’s roles are stored within an array on that User’ Doctrine entity.

I began crafting a form (using the Symfony Form component) to manage user details. When creating forms that are bound to Doctrine I’ve generally found that I’ve needed to do little in the way of form customisation; the form component does a good job of figuring out which form fields to use based on the type of the variable it is given. So name, being a string, gets modelled as a textfield, while their registration date, being a DateTime object, causes a series of select boxes to be created which allow dates and times to be entered. So far so good.

But of course there has to be a reason for a blog post, and this is mine: I wanted a checkbox to toggle on/of the administrator role for each user. Since roles are stored in an array on the bound entity, the default is to render a collection of fields, which leads to an array of values being submitted by the form. Trying to modify the field definition to a ‘single’ field, like a checkbox, led to an error as the Form component doesn’t know how to map an array to a single value. A multi-value field wasn’t an option as I didn’t want to expose the roles (which wouldn’t necessarily make sense to an end user), and I didn’t want to get into messing about with Twig templates if I could help it; a bit of Googling led me to this article on the cookbook, which describes how to dynamically add elements to forms using a Form event subscriber; this turned out to be just what I needed.

Reading through the cookbook article, the following plan took shape: when the form is created, add a checkbox to the form which is ticked depending on whether the User object bound to the form has the administrator role. When the form is submitted, if the checkbox is ticked, grant the user that role. If it is not, remove the role from their array of granted roles.

To implement this, I needed two classes; a Form class, of course, and a new class that implements Symfony\Component\EventDispatcher\EventSubscriberInterface and subscribes to events on the form. As in the cookbook example, when the ‘preSetData’ event fires I’d be adding a field to the form. In addition, when the ‘bind’ event fires, I’d be using the value of the field to modify the bound object, in this case the User being managed. This is what I ended up with:

I’m manually adding the subscriber to the form in UserType::buildForm(), which feels a bit weird when the usual approach would be to define a service and tag it appropriately. I’m not sure if that’s possible with Form subscribers, that’s just how the cookbook approach went. I’d imagine there are other ways I could have achieved the same result, but I like this approach because I don’t have to modify my User class at all, and I don’t have to delve into form field customisation.

The only downside I’ve found so far is that there doesn’t seem to be a way to order the fields that get added in the listener – they are always placed at the start of the collection, regardless of when the subscriber is attached to the form. This means that some template work is necessary to place the field as desired.

Deactivating a Macports install of XDebug in a LAMP environment

A few times I’ve found myself cursing when trying to toggle XDebug on and off via Macports. Typically I’ll be debugging with it enabled, then disable it for development/testing to get the fastest experience possible (it tends to really impact performance on large codebases, such as a Symfony2 standard install), only to experience segfaults when I refresh the page I’m working on.

The solution I’ve found is when restarting Apache (which is necessary for the change to PHP’s installed modules takes effect), to use an explicit start/stop rather than a restart. According to the Apache docs restarting only kills off children processes, so the parent remains running:

Sending the HUP or restart signal to the parent causes it to kill off its children like in TERM, but the parent doesn’t exit. It re-reads its configuration files, and re-opens any log files. Then it spawns a new set of children and continues serving hits.

I imagine this leading to a discrepancy in the loaded PHP modules, which causes the issue.

So when wanting to toggle XDebug, I use these commands:

Install (first time only):
sudo port install php5-xdebug

Disable:
sudo port deactivate php5-xdebug
sudo apachectl stop
sudo apachectl start

Enable:
sudo port activate php5-xdebug
sudo apachectl stop
sudo apachectl start

Jeff Atwood is a muppet.

I was having a nice, relaxing Saturday morning until I read through my Twitter timeline and was directed to Jeff Atwood’s latest post on Coding Horror, “The PHP Singularity“. After reading through it, and the comments from other readers, I got annoyed. Really annoyed.

I won’t repeat the article, but the gist of it is:

  • PHP is a horrible language
  • Something must be done
  • Jeff is the person to do it

I quite enjoy blogging but I don’t do it very often. I try to make sure anything I talk about is well researched, because a baseless opinion is worthless, but I don’t have a lot of free time – so if I don’t have something I consider worth saying, I don’t say it.

Jeff doesn’t have the same concern. You may wonder why I read his blog, given that I clearly take exception to some of its content, but the funny thing is that when talking about things he is knowledgable of, he has some great advice.

Like when he talks about his children, because he obviously knows them, or routers, where he’s clearly done some investigation. Now, I’m about to become a father, so I really enjoyed the former post, and if I needed to buy a router, I’d probably just be lazy and pick one from the latter because he knows a lot more about them than I do.

But here’s the thing. Jeff doesn’t seem to know much about PHP. I’d guess he’s read some posts about it, seen a few Q&As on Stack Overflow about it (a site he deserves massive kudos for), read through the PHP Manual, whatever – but he’s not a PHP developer. When he says PHP is ‘terrible’ or ‘deeply flawed’, I wonder how he’s come to that conclusion? Has he ever developed anything substantial in PHP? What is he basing this opinion on? He’s played with his children, he’s bought and installed a router. But when it comes to PHP, is the extent of his knowledge that which he has gleaned from others? Because if that’s the case, he really should think twice about offering his opinion on it.

The most glaring statement in the entire article is this one:

Therefore, I’d like to submit a humble suggestion to my fellow programmers. The next time you feel the urge to write Yet Another Epic Critique of PHP, consider that:

  1. We get it already. PHP is horrible, but it’s used everywhere. Guess what? It was just as horrible in 2008. And 2005. And 2002. There’s a pattern here, but it’s subtle. You have to look very closely to see it. On second thought, never mind. You’re probably not smart enough to figure it out.
  2. The best way to combat something as pervasively and institutionally awful as PHP is not to point out all its (many, many, many) faults, but to build compelling alternatives and make sure these alternatives are equally pervasive, as easy to set up and use as possible.

How anyone can offer a ‘humble’ suggestion and then go on to question the reader’s intelligence is besides the point (though it does nicely illustrate Jeff’s technique of drawing the reader in with deference only to hit them with a massive dose of self-righteousness) – but there’s two things I really take exception to here. Firstly, as anyone who has spent any real time with PHP knows, the language is far, far different now to what it was in 2002. For heaven’s sake, PHP5 (with a brand new object model that made proper OOP possible) didn’t make its debut ’til 2004, and support for register_globals (one of the worst features of PHP, ever) was removed in the most recent version, 5.4. Those facts are available under PHP’s entry on Wikipedia, but perhaps Jeff’s not smart enough to Google the history of PHP before commenting on it?

Secondly; assuming for a second that PHP is as horrible as he deems it to be – the best way to ‘combat’ it isn’t to ‘build compelling alternatives’ and ‘make sure these alternatives are equally pervasive, as easy to set up and use as possible’ – no, the ‘best’ thing to do (considering the amount of developers and sites worldwide who depend on the language and are getting things done with it every single day) is get involved with and actually understand PHP – read the internals mailing list, make requests for comments, code contributions, etc. It’s a silly person who decides to try something new before attempting to fix what’s broken, when there is so much invested in it. Perhaps if Jeff wasn’t trying to drum up interest in this new project of his, he’d have been a little less inflammatory?

Look, as someone who has used PHP successfully for the last decade, obviously I’m going to disagree with Jeff’s opinion. But the language has not only helped me get a great job, a nice house, and will shortly be helping me pay for one of those baby things, it’s also made Facebook the biggest website in the world, and enabled Yahoo! to build (ok, and throw away, but it’s not PHP’s fault) an empire. When Jeff’s got off his soap box and tried to build something equally successful in PHP and failed, I’ll start taking his opinion seriously.

As I said, I don’t like making statements unless I’ve researched them fully. I’ve read Coding Horror for a long time, and I feel qualified to say that Jeff Atwood is a muppet.

Resources for learning Symfony2

I’ve been asked a few times what the best resources are for learning Symfony2. With the project still relatively young there aren’t yet (to my knowledge, anyway!) any books (physical or otherwise) on Symfony2 available, but there is a good amount of information in the form of manuals and tutorials on the web to get on with.

This question on Stack Overflow lists most of them; specifically:

  • The Book: The official documentation, also available as a PDF download from the same location. The best place to start, and covers most of Symfony’s functionality, but doesn’t have many ‘real-world’ examples, as opposed to…
  • The Cookbook: Complements The Book by providing some more complicated examples of how Symfony2 can be used – sometimes the example you’re desperately searching for doesn’t feature, but on the whole it’s necessary reading to understand what Symfony2′s capable of and the best ways to use it.
  • It’s not strictly a Symfony2 resource, but Fabien Potencier’s ‘Build your own framework’ series of articles use the same components that make up Symfony2 to construct a similar framework, and as such are a really good way to familiarise oneself with the building blocks often become invaluable when trying to accomplish anything complex with Symfony2.

That’s it in terms of ‘official’ resources. There are some really good community efforts too, including:

  • A series of screencasts at KnpUniversity which introduce the key features of Symfony2, from installation and configuration through to security, forms, and using Doctrine to work with data sources. These cost $$$, and I haven’t tried them myself, but KnpLabs have been very involved with the development of Symfony2 so they’re probably well worth a look.
  • The Symblog tutorial is an excellent step-by-step guide to building a blog in Symfony2, covering most of the essential topics, in the spirit of the Jobeet tutorial from the original Symfony framework. Each part of the tutorial points to related articles in the official documentation, so it’s a nice way to work through that while building something tangible.
  • Speaking of the Jobeet tutorial, there’s also a companion tutorial for Symfony2. Like the Symblog tutorial, this explains the MVC approach to development with Symfony2 and dips into functional/unit testing too.
  • I’ve found the PHP and Symfony blog to be one of the best for learning about less common features of the framework, the sort of topics that are crucial when going beyond building the simple blog apps.
  • Richard Miller‘s blog is also excellent for the same reason.

Each of those resources will probably give anyone with decent PHP experience enough information to start building applications with the framework. Questions will inevitably arise, in which case go to the following places for help:

  • The Symfony2 Google Group is handy because often the problem you have has been answered already, so it’s a good resource as well as somewhere to get help from others using the framework.
  • The Symfony2 IRC Channel is good for real-time assistance, and is populated with both experts and newbies. Following the chat is a great way to pick up hints and tips for problems you have yet to encounter.

If there are other good resources that I’ve missed, please let me know and I’ll add them. I’ll try to keep this article up to date in future as new resources emerge.

It’s a kind of ImageMagick – installing the PHP extension for Windows 7.

I had a bit of a nightmare recently trying to get the ImageMagick PHP extension working on Windows. Builds of the extension as a DLL are provided by Mikko, which is awesome, but I had some trouble getting it to work.

The workstation I was using was running 64-bit Windows 7N, and the issue I was seeing was that the extension was being registered (if I ran php -m from the command line it seemed to be loaded) but when inspecting phpinfo() output the module was conspicuous by its absence.

Windows 7N is an EU version of Windows that comes without the Media Player framework – presumably an anti-trust related provision. Upon inspecting the extension DLL with Dependency Walker I discovered that it was linked to several missing DLLs that are supplied by the Media Player framework, and an additional DLL, IEShims.dll, which is an Internet Explorer library.

I installed the Media Feature Pack which resolved the majority of the missing DLLs. I also copied IEShims.dll from Program Files\Internet Explorer to Windows\SystemWOW64 (this probably wasn’t a good idea as the architectures of the DLLs will be fundamentally different, SystemWOW64 expects 32-bit DLLs – but I haven’t encountered any adverse effects as yet). After doing this the extension began to work as expected, and was visible in phpinfo() output.

There was a crucial comment on Mikko’s blog that I’ll repeat here – if the workstation is running PHP under IIS/FastCGI, install version 6.6.2-10 or earlier of ImageMagick (available from http://image_magick.veidrodis.com/image_magick/). Don’t install any versions later than that – they were built with VC10 and will not be compatible with the extension, which was built with VC9.

Finally, when I attempted to use the extension (I wanted to convert some images from SVG to PNG) I ran into errors because ImageMagick defaults to using the Windows temp directory as its conversion directory, and IUSR doesn’t have rights to write there. Rather than add it to the permitted users list (not a very secure approach) I set the IMAGICK_TMP environment system variable to a less prominent location; this required a restart to take effect.

For the social good – Box UK Hackday #1 recap

On the twentieth of November, 2011, the company for whom I work (Box UK) held a hackday in Cardiff at the Student’s Union. It was the first time that we’d organised such an event, but it seemed to go really well – feedback from the participants was good, it was well attended, and personally I had a really good (if stressful!) time.

The theme of the hackday was ‘For the social good’ – applications built during the day had to have some sort of social theme, ideally to improve the lives of the people that would use them. That’s quite a broad topic, and it resulted in an array of different apps – not just in the sense of intended purpose, but in style, and also in platform. While teams typically used scripting languages to build their apps within those used (PHP, JavaScript, Python) were a lot of varied frameworks (Symfony2, Lithium, Django, jQuery Mobile, Node.js, PhoneGap and more), as well as SQL and No-SQL solutions alike. I initially suggested creating an iOS app, until it was pointed out to me that the verbose nature of Cocoa meant we’d probably only get one class done in the 8.5 hours we had!

My team comprised of myself; Paul, a former colleague, and Tom, a 3rd Year student at Cardiff University. Paul and I had decided to try to create a mobile app that used geolocation to provide the user with trivia and quizzes for the places of interest around them; we were only going to concern ourselves with Cardiff, so it would be a tourist aid for the city, or perhaps a learning tool for schoolchildren. Tom then joined us, and had originally wanted to work on a Corkboard-style app – after a discussion we modified that into a Q&A app which would be incorporated into our exploration tool idea, so the user could additionally ask questions and receive answers in realtime. That was the idea, anyway. We had 8.5 hours to implement it!

Photo courtesy of dangreenphotography.com

We split our responsibilities up such that Paul would build the mobile app (he plumped for jQuery mobile, version 1 of which having been released just days earlier), Tom would build an app to aggregate questions from users and allow a pool of authors to submit replies (he wanted to use Cappuccino), and I would build the webservice/content management system both apps would run on (I thought Symfony2 would be a good framework). It sounded good in theory, but then it always does.

I’ve dabbled with Symfony2 since it was in beta so I knew what it could do, but not necessarily how to make it do it. So the first hour of the day was spent scanning the documentation and looking through the available ‘bundles’ (Symfony nomenclature for packages of redistributable code) to see what community efforts I could re-use. I came across the SonataAdminBundle relatively quickly and it seemed a good fit – its purpose is to generate a CRUD interface for the models within the application’s domain. This would give me a quick way to add and manipulate the data in the app, so I plumped for it. I guess it’s a bit risky using an unknown in a hackday since if it turns out to be unsuitable, there’s not a lot of time to try something else – but I thankfully had no such problem here.

The SonataAdminBundle is impressive, in that with relatively little configuration and code I had a very functional app. The project documentation assumes a fair bit of Symfony2 knowledge from the developer, which isn’t ideal in a high pressure scenario where I didn’t really have time to read the source code, but I’d worked it out by lunchtime. I’d say within a couple of hours I had an app with which I could create models, specify forms which related to them, and manage data.

Most of the rest of my day was spent working with Doctrine2, a PHP ORM that is tightly integrated with Symfony2 and the SonataAdminBundle. Doctrine2 I found to be the perfect tool for a hackday – create a class, put some annotations on properties to define the type of the field, and any relationship to other classes, then run a command line script which generates all the accessor code, and even updates the database schema – saving a substantial bit of work. There were some hiccups along the way, but I did manage to get a webservice together which could supply Paul and Tom’s apps with data.

By this point we were running quite low on time (I think I spent too long chowing down on the copious amounts of free pizza!), and so rather guiltily I left the other members of the team with only an hour to integrate the webservice into their apps – both were true heroes though, quickly turning everything around so that we could demo something fully featured to the other teams.

Each of the other teams not only produced an app (I’ve been to hackdays where people don’t even get something together to demo, which is a little disappointing) but it was also gratifying to see that each app was functional, innovative and different. My personal favourite was Tomazs’ mobile app for the Welsh Premier League (it doesn’t get enough love!), but the grit.ly team (who produced a mashup of several data sources to plot on a UK map areas at risk of accidents due to poor weather and lack of gritting), who won first prize, and a team of several 1st year Cardiff Uni students with another former colleague at Box UK, Warren Seymour, who took second with a cool Corkboard app for university students, thoroughly deserved their awards.

It was also great to see Tom take the best individual developer prize, as he demonstrated some serious coding chops despite having to wait until the very last for the data his app depended on. He also ran into some issues with Cappuccino during the day, and rather than abandon what he was doing, he just switched to Prototype and got on with it in a very pragmatic fashion.

As a bonus, after the prizes were handed out we decamped for a drink in the Tafarn, something I haven’t done since leaving Cardiff University 10 years ago. It was almost worth attending the event solely for the excuse to walk down memory lane!

The code for the CMS app I built can be found on my Github page. Time permitting, I’d like to take the idea a bit further; though it’ll require a bit more planning than the 15 mins it got on Sunday to be a proper success!

Using a PHP framework with Windows Azure

[This is a blog post related to the PHP on Azure competition.]

It’s been a while since my last PHP on Azure contest post, mostly due to commitments @work that have reduced my free time considerably. There’s not long left ’til the competition closes though (I have a week), so I need to get my skates on!

Casting my mind back to my last post, I was able to finally deploy to the local development fabric. In the interim I’ve set up an Azure account and successfully deployed a simple script to the cloud, so everything’s fine on that front. It’s time to start developing my application.

Since my time is limited my application will be quite straightforward – a CMS to manage media files. This should allow me to use all the features of Azure (queuing, table storage, blobs) I’m interested in.

Bittersweet Symfony

The first step in building the application is to decide on  framework to speed up development. The main reason I got into the contest in the first place was because I wanted to have more experience with Zend Framework – while I’d used its components in isolation before I’d never built an application with it. However in the months since I entered the competition I’ve started using Symfony 2 heavily. That, and the realisation that ZF2 is around the corner, have made me think that ZF isn’t the best choice for this contest, so I decided to use Symfony 2 instead.

That was easier said than done. I dropped the Symfony framework into my Azure WebRole project, and put together a ‘hello world’ script, only to immediately run into this issue – apparently Azure has issues when building projects when paths to files or directories exceed 260 characters. Of course, in a framework of Symfony’s size, with many nested directories, this limit is unrealistic.The solutions recommended on Jim’s blog include changing the project paths to be shorter (impossible in this case) and setting a temporary environment variable which moves the location at which Azure builds projects, thus reducing the prefix of any paths. As Jim says, this isn’t a guaranteed fix and indeed, it didn’t work for me.

So including Symfony within the WebRole didn’t seem to be possible. I experimented with including in within my PHP include path, in the hope that it would save some characters, but that didn’t work at all, Azure didn’t even pick it up. I need to look around the net to see how Azure manages include paths, since it’s something I use often in PHP. How do PEAR modules work, I wonder? Can you manage PEAR within Azure as you would with a local PHP installation, or do you have to place the components within each WebRole? Topics for future posts, maybe.

Anyway, it didn’t look like Symfony was going to work any time soon, so I needed an alternative, and since Ben Waine had successfully deployed using Zend Framework I thought briefly of using that after all. Then, I came across Silex.

Along came a Silex

Silex is a micro-framework based on Symfony 2 components, inspired by Sinatra, the Ruby on Rails framework which presents an alternative to typical MVC web applications. It’s succinct and straightforward, and, crucially, is deployed as a PHAR archive. This means I only need to include a single file in the root of my project to be able to use the library – which means no long paths that Azure can’t handle.

I downloaded the Silex archive from its website and dropped it into the root of my project, then copied the ‘hello world’ example provided within the Silex documentation into my index.php file:

require_once __DIR__.'/silex.phar'; 

$app = new Silex\Application(); 

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

$app->run();

Then I deployed my project to dev fabric, and navigated to /hello/Craig. Of course, this didn’t work immediately – nothing ever does for me – because I didn’t have a web.config file set up to send all requests through the front controller, index.php. I got an IIS 404 page rather than the ‘Hello Craig’ I was expecting. So I used IIS’s Apache config importer to convert the sample .htaccess file provided by Silex into a web.config file, then copied the relevant rewrite rules into my WebRole’s config file. Rebuilding the application resulted in a working application. Good to go!

Here’s what I needed to add to my web.config file in case it’s of any use to anyone:

Compiling Silex on Windows

Because Silex is pretty new I’m expecting to find issues here and there, plus when working on Windows I’m accustomed to having to make little changes here and there to get PHP code that’s been written on *nix to run properly – so I wanted to build the Silex PHAR from source so I could make changes if necessary and properly understand how everything fits together.

This is quite straightfoward. First, I checked out Silex from its github page:

git clone https://github.com/fabpot/Silex.git silex

I merged in a pending fix which addresses compilation issues on Windows – there’s probably a fancy way to do this in git but I just applied the fix manually.

Then I needed to get Silex’s dependencies:

git submodule init
git submodule update --recursive

Silex provides a PHP script, named ‘compile’, which puts the archive together. I had to make some changes to my php.ini file before I could run it successfully:

phar.readonly = Off
phar.require_hash = Off

Then creating the archive was as simple as running:

php compile

Using Eclipse to run PHP in Azure DevFabric

[This is a blog post related to the PHP on Azure competition.]

As detailed in my last blog post I had some… problems getting a PHP/Azure development environment set up after creating a Windows 7 partition. Well, I scrapped the partition, said goodbye to my old XP OS and started afresh, and that looks to have done the trick – I’m finally able to deploy PHP applications to development storage on my local machine. I’m none the wiser as to why it didn’t work the first time, which is annoying, but at least it’s working now.

After I reinstalled Windows 7 I took care to install all the automatic updates before I went near any other programmes. After a lot of rebooting I eventually installed IIS and, through the Web Platform Installer, the Azure SDK and the Azure command line tools for PHP, along with their dependencies. Then, I installed Eclipse PDT and, following this excellent article, the Azure plugin for eclipse that Brian Swan wrote a great tutorial on.

I came across a few issues while doing all this that I should detail:

  • I had to set Eclipse to run as an administrator (right click eclipse.exe-> properties -> Compatibility -> Run as administrator) before it would install the plugin and allow me to use it within the application
  • I signed up for the free introductory trial of Azure so that I could follow the tutorial properly and configure a database on Azure

It’s a bit annoying that even when developing an app one has to run against SQL Azure in the cloud (which will eventually incur costs). I’d assumed I’d be able to use SQL Server locally but that doesn’t seem to be the case. Some sort of free quota for use in the development stage would make sense to me.

The really good thing about using the Eclipse plugin is that it brings together the many disparate projects that one needs to leverage to work with PHP on Azure. When I was trying to install all this stuff on my own I got a bit muddled, especially since some of the libraries are installed through the Web Platform Installer. The other advantage of the plugin is one can deploy to the cloud from within Eclipse. I’m not a fan of the Eclipse platform but I have to say in this case it’s a good experience (especially since the alternative is the command line!).

If I’ve one criticism of the documentation Microsoft provide (which is generally well-written and thorough) it’s that there’s no ‘official’ site for PHP on Azure which gives a simple one-page overview of everything – after reading about this stuff for over two weeks I still don’t feel like I’ve grokked it, and without blogs like Brian’s and Maarten’s I’d be struggling. As a PHP developer I’m used to the awesome PHP manual and its direct approach to documentation and perhaps Azure (as far as PHP is concerned) could do with something similar. For developers like me, who are new to Azure and trying to get up to speed quickly in a short space of time (and with little time to read around) that sort of resource would be invaluable.

For the moment though I’m just happy that I can finally start developing my application. It’s been a frustrating week battling to get to the point where I can just write a line of code, but from here on in hopefully it’ll be worth it.

24 hours of Windows

[This is a blog post related to the PHP on Azure competition.]

I’m sure everyone blogging about this contest will at some point write a post describing their experiences setting up an Azure development environment, but writing two posts a week is hard, so I can’t pass up an easy topic! Mine won’t be terribly formal since there are plenty of guides out there that already do that, so: from a clean Windows 7 install, here’s a minute-by-minute style guide to getting a PHP on Azure development machine configured. I’m going to try to stay away from as many guides and tutorials as possible to see how intuitive this process is.

The following takes place between 9.43pm and 01.56am on 02/03 March 2011.

9.43 pm

The previous two hours involved me creating a new hard drive partition alongside my XP install and installing Windows 7 into it.  I’m using the free Enterprise trial for the time being. After booting for the first time, I install some Windows updates and reboot. The next thing I do is open Internet Explorer 8, search for Google Chrome and install it. IE’s come a long way recently, but it’ll have to go a lot further before I use it as my main browser. I write the intro to this blog post, and that takes us up to where we are now.

9.26

I go here and download the Microsoft Web Platform installer, a neat utility which allows developers to install both products such as IIS and PHP, and web applications like WordPress and Drupal. Looking through the list I remember that Windows 7 (Enterprise edition, at least) comes bundled with IIS, so I think I’d better install through Windows to avoid confusion.

9.31

I go into the add/remove Windows features programs bit in Control Panel and check the Internet Information Services option which installs IIS with the default settings.

9.33

I open up IIS Manager, and all seems OK. I hit http://localhost in Chrome and I get the delightful IIS7 landing page. Web server: check. Painless.

The IIS7 landing page.

9.38

I think I’ll add a picture of the IIS7 page since it looks so nice, and it gives me an excuse to try the new Paint application (which I think is a Windows 7 thing, though it may have come with Vista. I’ll never know). Paint’s a lot better these days, that’s for sure.

9.40

I run the Web Platform Installer (henceforth WPI) and select the Products tab. There’s plenty of stuff in there that looks cool, but for now I’m only going to bother with the essentials, so I choose:

  • SQL Server Express 2008
  • Windows Azure command line tools for PHP (sounds like that’ll come in handy!)
  • PHP Manager for IIS (I’ve used this in work, it makes configuring PHP for Windows a breeze)
  • PHP 5.3.5 for WebMatrix (not sure what the WebMatrix bit is about, but it’s nice to see the latest version of PHP in there)

There’s a whole bunch of other stuff there that looks like it’ll come in handy, but the above should get me to a point where I can get a PHP script running so we’ll start there. I hit install, and see A LOT of dependencies which will also be downloaded. Turns out the PHP 5.3.5 for WebMatrix install is a little bit of PHP, and a whole lot of WebMatrix – and PHP 5.3.5 is already being downloaded as a dependency of the Windows Azure command line tools. I’m a little freaked out, and decide to untick the WebMatrix trojan horse and just try installing PHP on its own for now until I discover that I need anything else.

Since I’m installing SQL Server, I get asked to set a password (I don’t have to, I could use Windows authentication, but I figure it’s safer). I choose a suitably fiendish one.

This could take a while, so I go downstairs for a chat with my wife and a cup of tea.

22.03

I come back to a screen notifying me that all programmes but SQL Server installed correctly. I open the install log to find out why, and would you believe it – my password wasn’t strong enough! Lesson learned. OK, another go, this time with a tougher password. I also add in the SQL Server Management Studio application for working with SQL Server which I’d missed the first time round.

22.16

It’s taking ages to install SQL Server Management Studio, so I go back and rewrite the intro which somehow is in a completely different tense to the rest of the article. I look at the copy of Strunk and White on my desk and realise I need to read more than the 10 pages of it that I’ve managed to date.

22.18

And at that moment, the installer finishes. No error messages this time, which means I’ve got l33t pa55w0rd skillz. Now to check if PHP is working.

22.25

I open up a command prompt and type ‘php’ into it. Hit return. Error message – PHP isn’t recognised.

A familiar sight on Windows

Usually this means that PHP isn’t in Windows’ PATH, so I probably need to do that. Hmm. Where’s the WPI put PHP? I find it under Program Files. Add that to the end of the path variable. Restart the cmd prompt. PHP is now responding, and the version is listed as 5.3.5. Fantastic.

That's better.

22.38

I’m curious as to what modules come bundled with PHP when it’s installed via the WPI, so I’m going to check that out. I could do it through the command line with the -m switch but I also want to check the PHP manager for IIS is running, and configure PHP for IIS at the same time.

I open up IIS and select the default web site, then select the PHP Manager module. It tells me that my PHP configuration isn’t correct, and offers to set the default document for the website to index.php and monitor my php.ini file for changes, both of which are helpful suggestions. I do both. IIS seems to have picked up the correct version of PHP, so all is well in that regard.

22.43

The default web site is pointing to C:\inetpub\wwwroot, and it’s got some random stuff in it. I delete both the default web site and the files, then create a new site. I create a new one called ‘localhost’ and set it to respond to ‘localhost’. I try to add PHP file called index.php which outputs phpinfo(), but I don’t have administrator rights for this folder. Grr. I add myself with read / write permissions, and save the file successfully.

22.49

I hit http://localhost in the browser, and wow – it’s working. The PHP interpreter, FastCGI as the SAPI – and all with pretty much zero configuration. Take it from someone who spent a good few evenings last year building a LAMP server from source and configuring PHP in Apache – this is impressive. OK, so I’ve done a lot of this before, but having the WPI take a lot of the grunt work away is so helpful. Also I always have to check which version of PHP I need on Windows – is it non-thread-safe? Thread-safe? VC6? VC9? It’s nice having all that uncertainty taken away.

The PHPInfo page, courtesy IIS

I take a look at the modules list. The usual suspects, nothing too fancy. I’m surprised to see that the Microsoft SQL Server Driver for PHP isn’t on there, I assumed that would be bundled. I think I saw it in the WPI, actually. I’ve a few can’t-live-without modules like PECL HTTP and XDebug that I’ll have to add in due course.

22.59

OK, it’s getting late – time to wrap this up. I need to find a ‘my first Azure app’ tutorial on the web and make sure I can run it.

It doesn’t take much Googling to come across this article, which seems to be exactly what I’m looking for. I’m not too bothered about deploying to the cloud just yet, I just want to make sure I can develop on my local machine for now.

I seem to have covered the first few steps already (they’re concerned with the Azure command line tools for PHP which I installed via the WPI earlier – that article could do with an update to notify others in a similar position), so I skip on and open up the Azure SDK command prompt.

23.23

I keep following the steps, successfully creating a file and a temporary project. I come to packaging the project with the package.php script, and deploying to DevFabric, and get the following error:

Runtime Exception: 0: Default document “ServiceDefinition.rd” does not exist in Service directory “ServiceDefinition.csx”!

No idea. Google tells me nothing. Maybe I missed something in the earlier part of the tutorial.

Runtime Exception: 0: Default document “ServiceDefinition.rd” does not exist in Service directory “ServiceDefinition.csx”!

23.27

OK, looks like I might have needed to start the Compute Emulator. Let’s try that… Oh, and the Storage Emulator too.

23.29

Nope, that doesn’t fix it. I’d better re-read through everything in case I missed something.

23.42

I read through the package script code to see where things are going wrong. I see quickly enough where it attempts to reference the missing file, leading to the exception, but there doesn’t appear to be a point where the file is actually created. Is it supposed to be copied from somewhere? I can’t see anything obvious and there’s nothing on Google that mentions what that file is or where it comes from.

This isn’t good. My ass is nowhere near Vegas at the moment!

01.56

I’m totally out of ideas, and I’m not above begging for help, so I contact Maarten Balliauw (who has published a lot of material on PHP on Azure) via Twitter to see if he’s seen the error before and can point me in the right direction. He kindly offers to put me in touch with someone involved in creating the tools, and in the middle of MVP 2011 festivities too!

02.11

Since I’ve followed the instructions in the articles to the letter, I’m wondering if Windows is to blame. I’m noticing other weird behaviour on my machine. Windows suggests folders to me in the command line that don’t exist; it’s been using my external hard drive to store installers from WPI; when I try to restart my machine to see if that’ll cure the problem it tries, and fails, to install Windows updates. Perhaps running Windows on a partition alongside XP wasn’t such a good idea after all. I decide enough’s enough, and go to bed frustrated.

The Next Day

Despite having slept on it and coming back fresh I’m still having the same problems, and am less confident in my installation in general. It’s possible there may be a bug in the Azure tooling, but given I’m having other issues I think the best thing to do is to take the plunge and install Windows 7 onto a dedicated drive, in case there are conflicts arising from sharing one with XP (I don’t see how that could be the case, but strange things are definitely happening).

I’m a little disappointed because things seemed to be going very smoothly right up until the last hurdle. The WPI, with its dependency management, makes it so easy – I’ve since learned I need only to have installed the Azure Command Line Tools for PHP to have got everything else automatically, which is neat.

So I now face my second install of Windows 7 in 24 hours – a task I think even Jack Bauer would blanch at :-)

I’d like to thank Maarten for helping me out when I was seriously fed up. Hopefully after a re-install this problem will go away and I can finally start developing. Fingers crossed!