My Sister’s Graduation

Yesterday I attended my little sister’s graduation ceremony – she has a BA in Early Childhood Studies from University College Birmingham and I am so proud of her I can’t actually express it! She’s worked hard to get to here and the path was not always smooth. I uploaded a selection of pictures from yesterday to remember the day by.

I’m also very pleased to have been able to be here to cheer her on and also very pleased that we now have the sequel to a photograph taken at my own graduation day 5 years ago.

One in the gown, one in the hat One in the hat, one in the gown

Well done, little one!!

Update from ZendCon

I’m currently in California, at ZendCon. I’m having way too much fun to blog but there is a writeup on the phpwomen site of my experiences so far. I’ve met some great people, and its long days but I’m learning a lot! I’ve (been) volunteered for an uncon session later on today, at 5:15 I’ll be speaking alongside Matthew Weier O’Phinney on “Subversion Tips and Tricks” – if you’re here at ZendCon then drop in and say hi.

For everything else, see the zendcon photos on flickr! http://www.flickr.com/photos/tags/zendcon08

Using curl and PHP to talk to a REST service

Having recently written articles about curl and about writing a PHP REST server, I thought I’d complete the circle and put here a few notes on using PHP’s curl wrapper as a Rest client. Also I had to look some of this up when I needed to actually do it so next time I need only look in one place!

If you don’t know about PHP, Rest, or curl, then I recommend you do a little reading around each of those subjects before reading this as its unlikely to make much sense – I’m not including background on these topics as there are better resources elsewhere.

I’ve written about using curl before from the command line, but this example uses PHP’s curl to access the service. This is just a simple example, but hopefully if you are doing something along these lines you can adapt for your needs.

In the example, we set the URL we’d like to call and initialise the curl object to point to that. Then we create an array of post data, and configure curl to use POST to make the request and to use our data array.

       $service_url = 'http://example.com/rest/user/';
       $curl = curl_init($service_url);
       $curl_post_data = array(
            "user_id" => 42,
            "emailaddress" => '[email protected]',
            );
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($curl, CURLOPT_POST, true);
       curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
       $curl_response = curl_exec($curl);
       curl_close($curl);

       $xml = new SimpleXMLElement($curl_response);

We execute the request and capture the response. Health warning: by default curl will echo the response (for reasons that aren’t clear to me), if you want to parse it then you will need to use the CURLOPT_RETURNTRANSFER flag to have curl return the response rather than a boolean indication of success – this fooled me completely for a while, I have no idea why it works this way. As you can see I’ve parsed the resulting XML and my script can then continue with the data it acquired. Depending what you need to do next, you can manipulate the SimpleXMLElement object as you need to.

If you’re working with PHP and services, then hopefully this will get you started, if you have any questions or comments, then please add them below!

PHPNW Update

With just over a week remaining on the PHP North West Call for Papers, plans for this Manchester-based conference are fairly racing along. The call for papers closes on 21st September (in time for me arriving home from ZendCon so we can make some decisions before I shoot off again). So far the submissions have been of a very high quality and I’m really excited about this event. In addition we have confirmed Derick Rethans as one of the keynote speakers, more details about that on the PHPNW site itself.

Tickets will be on sale somewhere around the end of September or beginning of October, and we’re already finalising some of the sponsorships – thanks so much to the companies who are getting involved in the event. So many of them are really adding to the experience as well as just buying advertising space, its giving the event a very special feel. I’m looking forward to seeing at least some of you in Manchester on November 22nd!!

Crochet Tutorial: Granny Square Round 2

Here’s the last in the crochet tutorial series, showing how to fit a second round of granny square onto the existing “granny’s daughter” that we made previously. I’ll have to take some photos of stuff I’ve done with this pattern to give you some ideas of what can actually be made from this very simple pattern piece. Anyway, enough waffle, here’s the video:

If you get this far – definitely let me know :)

Acer Aspire One and an XD Card

I may have mentioned my new acer aspire one already, and I probably also mentioned the problems I had with it not reading my camera card. The camera is a Fuji Finepix, and the card is a 2GB XD card – XD is the format used by Fuji and by Olympus apparently.

Well, we went back to the shop and demonstrated the card not working. They took the card, tried it in their card reader (it worked, just like it does in my card reader and in the camera). Then they tried it in the display model of the same machine, and it persisted in not working. After a whole rigamarole of contacting the supplier, who told us to contact the retailer, who told us to go home and ring their central helpline, who told us to contact the supplier (which went on for a while) we went back to the shop again and they got a new XD card, and it worked absolutely fine. The new card is a 2GB card just like the old one.

Things I notice about this:

  • The old card doesn’t work even after formatting
  • The camera boots MUCH faster with the new card in it
  • I have no idea what could cause that

Anyway, I take it all back, XD cards do work with the linux acer aspire ones – and now I’m all set for being able to upload photos from my trip to ZendCon next week.

Laceweight Purple Mohair

I am a habitual chunky-yarn knitter. I will go all the way down to double knit weight, but beyond that I find life is too short to bother :) The upshot of this is that my projects get very big very quickly. I have a few trips coming up where I have long flights, and basically with an 18 hour travel time, I can knit about one hand-lugged-sized quantity of wool!! So I’ve been looking for something more portable to take as my project.

I’ve got this laceweight mohair from http://www.thenaturaldyestudio.com/ and its absolutely gorgeous. The pattern calls for Rohan Kidsilk Haze, which I know is lovely but it really is quite pricey.

laceweight mohair laceweight mohair - in a ball

One of the skeins (I have three!) was wound into a ball by friends when I took it to the knitting group, its 400 yards per skein so I can’t imagine I’m going to manage to crochet all that while I’m away.

The pattern is “Beaded Cobweb Wrap” from Erica Knight’s Essential Crochet, uses a 6mm hook so the pattern is more space than yarn anyway, and it looks quite easy once you’ve done the cast on – its crocheted longways, so there’s a mad long chain that you have to hook into to start with, something I always struggle with. I’ve been assured it’ll look like chewed string until I block it and that I should just carry on regardless – I’ll let you know how I get on :)

PHP Rest Server (part 3 of 3)

Edit: I have a newer series of articles on this topic. You can start reading here :)

This is part 3 of my article about writing a restful service server. If you haven’t already, you might like to read part 1 (covering the core library and grabbing the information we need from the incoming request) and part 2 (covering the service handler itself) before reading this section. This part covers the Response object that I used to return the data to the user in the correct format.

XML Response Object

Exactly what output you want from your service completely depends on the specification and what you are actually trying to do. I wrote a really simple response wrapper that responds with an outline tag containing a status, and then either the content or some error details. Here’s my response class:

class Response {

    public function output() {
        header('Content-type: text/xml');
        echo '';
        echo "\n";
        echo '';
        echo "\n";

        foreach($this as $prop_key => $prop_value) {
            if(!is_array($prop_value)) {
                echo '<'.$prop_key.'>';
                echo $prop_value;
                echo '';
                echo "\n";
            } else {
                echo '<'.$prop_key.'>';
                echo "\n";
                foreach($prop_value as $array_key => $array_value) {
                    echo '<'.$array_key.'>';
                    echo $array_value;
                    echo '';
                    echo "\n";
                }
                echo '';
                echo "\n";
            }
        }
        echo "\n";
    }
}

This could be more elegant and thorough, but its kind of an outline of what I did. Firstly set the content header, then the main tag. Then it loops through all the properties set against the response object and just writes them out as XML. Its very limited but at least its short enough to read easily! There is also an error response that gets called and returns the error type and message, setting the response status to “error” rather than “ok”.

REST Service in PHP

So there you have the ingredients for a REST server in PHP. I’m sure this isn’t the only way to solve this problem, but this is how I did it and I hope it helps someone. If you’ve got any questions, feel free to comment below – and if you do use this for a project, I’d love to hear from you :)

PHP Rest Server (part 2 of 3)

Edit: I have a newer series of articles on this topic. You can start reading here :)

This is part 2 of my rest service writing article. In part 1 we saw the library which holds the functionality we will be using, and we also handled the incoming request and captured all the data we’ll be using.

The REST Service

This is not really tricky but we’re pulling together lots of ideas at this point. So we have already got the incoming request data, and we’ve intialised an object with that data. We have a reference to the object which contains all the functionality we want. And we need to work out which of the library functions we should call, and then transform that data into a good format to return to the user. Let’s start with the handle() function:

    public function handle() {
        $urlParts = parse_url($this->url);
        // substring from 1 to avoid leading slash
        $this->_pathParts = split('/', substr($urlParts['path'], 1));

        // glue the first part of the path to the upper case request method to make a unique function name, e.g. usersGET
        $method = $this->_pathParts[0] . strtoupper($this->method);

        try {
            // now call the method in this class that wraps the one we actually want
            $this->$method();
            $this->response->output();
            return true;
        } catch (Service_Exception_Abstract $e) {
            $this->response->errorOutput($e);
        } catch (Exception $e) {
            die('An Unexpected Error Has Occurred');
        }
        return false;
    }

The rest of this class contains the functions, such as userGET, which call the real worker functions from the library class we originally created. The functions in this section look something like this, and they throw exceptions if anything goes wrong – you can see these being caught in the handle() method posted above:

    protected function userGET() {
        $this->response->user = $this->library->getUserDetails($this->getVars['user_id']);
        return true;
    }

I also use a magic __call() method to return sensible error messages if a user tries to call something that doesn’t exist (this was particularly helpful in development where not everything was there from the start!).

You can see here I’m using setting properties on the response object, but you could also just XML-ify and echo the output here if you wanted to. By using the response object however I am abstracting the XML transformation stuff and moving it to somewhere else so that it can be tested independently and even replaced as needed.

I’ll write about the response class and how that works in the third installment.

PHP Rest Server (part 1 of 3)

I recently had reason to write a REST server in PHP, which was very interesting. There aren’t a whole lot of resources on this topic around so I thought I’d write an outline of what I did. There is quite a lot to it so I’m publishing in multiple sections – this is part 1, which covers the central functionality and handling the incoming request.

Wrapping an Existing Class

The main functionality of the service was written in a class that had no awareness that it was a service – this is a similar approach to the one I described when I wrote about the PHP Soap Server – start with a normal functioning class and write some unit tests for it. The example I’m using today looks like this (my real version actually connects to the database and stuff but this is a nice mock of passing in a number and getting back an array):

class Library {
    public function getUserDetails($user_id) {
        $details = array(
            "user_id" => $user_id,
            "name" => 'Joe Bloggs',
            "email" => '[email protected]');
        return $details;
    }
}

In the soap article, you can see that wrapping a class takes just a few lines – for REST more code is required, but the idea is completely the same. In actual fact we started out with this as a soap service but then it was switched to rest – I only had to re-write the wrapper stuff and not any of the core functionality. Using the wrapper approach would also allow services to be published in multiple ways with the same underlying codebase.

Incoming Requests – Intialising the Wrapper

First of all I wrote a .htaccess file to direct all requests to the one controller file – so that all the different URLs would be handled in the same way.

As the requests came into here, I grabbed the data I needed and initialised the service class, something like this:

$service = new Rest_Service();
// instantiate the main functional class and pass to service
$library = new Library();
$service->setLibrary($library);
// create a response object and pass to service
$response = new Response();
$service->setResponse($response);

// set up some useful variables
$service->url = $_SERVER['REQUEST_URI'];
$service->method = $_SERVER['REQUEST_METHOD'];
$service->getArgs = $_GET;
$service->postArgs = $_POST;
parse_str(file_get_contents('php://input'), $service->putArgs);
parse_str(file_get_contents('php://input'), $service->deleteArgs);

$service->handle();

The variables are all read here and passed in to help decouple the systems – doing it this way allows us to initialise the Service with different incoming variables and/or a different library which can be really useful when testing, as it allows isolation of individual components. The syntax for getting the put and delete data is an interesting one, I wrote about this already in my post on accessing incoming PUT data from PHP, there are some helpful comments on that post as well.

To be continued … later parts will cover the service itself and the response format used.