Introduction to Zend_Db

I recently worked on a project which was based on Zend Framework – I haven’t worked with it before and I was temporarily confused by the existing implementation of some of the database-level stuff. After much reading and untangling of code, I’m now pretty clear how this should look, so here’s my overview. I’m not going to go into setting up a whole application, but this is a quick primer on how data models go together.

Modelling Tables

Zend_Db_Table is a class that represents a table. You instantiate one of these and call query functions against it. The actual code for my classes is really minimal, here’s an example:

class UserTable extends Zend_Db_Table
{
    protected $_name = 'users';
    protected $_rowClass = 'User';
}

The two properties that I’m setting here are all I use for basic tables. $_name tells Zend Framework which database table to use. $_rowClass tells it which class it should instantiate for the results from your select query. By default you’ll get Zend_Db_Table_Row objects but you can have it use any object which extends this class instead.

Getting Results

To get results from a table, you instantiate the relevant table class, and then fetch some results. You can restrict the results you get but Zend_Db_Select is a whole other kettle of fish that perhaps I’ll post about some other day. So a controller action might look something like this:

function viewAction()
{
    $users = new UserTable();
    $user_list = $users->fetchAll();
}

The $user_list variable will then hold an instance of Zend_Db_Rowset.

Working with Rowsets

The rowsets are iterators, you can loop over them and they will return objects which represent the rows in the resultset of the query. By default these are objects of type Zend_Db_Table_Row but if you set the table object’s rowClass, either in the object declaration or by calling setRowClass() before you fetch the results, then you can have any class which extends Zend_Db_Table_Row used. Its pretty common to pass the rowset straight to the view and iterate over it there – you can put any functionality you need for this object into the class you use. Let’s look at my user class for this example.

The Row Class

    class User extends Zend_Db_Table_Row
    {
        public function getName()
        {
            return $this->first_name . ' '.$this->last_name;
        }

        public function getProfileUrl()
        {
            return '/users/profile/id/' . $this->id;
        }
    }

These are overly simple examples, but giving this kind of functionality to the user model allows it to be re-used any place you need it. I’ve also found it useful to have an intermediate table row class that contains functionality that will be used by data from more than one table – for example for formatting dates in a consistent manner.

Zend Framework and Models

This is a pretty simple overview but it took me a while to get to this point – the framework does have documentation but its quite case-specific and doesn’t really show how it ties together. Now I understand these classes and their relationships, my development project is going a lot more smoothly.

PHPNW: One Month Countdown

In a month’s time I’ll be in Manchester, ready for the PHP North West conference. The conference is a one-day event (Saturday, 22nd November), although the social side of things will kick off the night before. Tickets are 50 GBP for the early bird, 35 GBP for students and concessions – so register now.

There are some amazing speakers, I hate picking out names, so go and look at the schedule and pick your own favourites to shortlist! As well as traditional hour-long conference slots, we’ve got a selection of shorter talks, plus a panel discussion at the end of the day … right before we party some more :)

Attendees get a year’s subscription to php|architect magazine with their tickets, and there will be sponsors and other exhibitors there – including some interesting user and voluntary groups so plenty to see and plenty of people to talk to. There are also some very nice giveaways so look out for those if you are there.

All in all, its a pretty exciting event, there hasn’t been anything like it outside of London that I know of for a while – and with the London conference still months away, this is a great chance to get to meet a few people and also pick up some new technical ideas in the meantime. If you’re coming, let me know so I can say “hi” at the event itself – looking forward to meeting you :)

PHPNW Tickets On Sale

Tickets are now on sale for PHPNW – the PHP Conference in Manchester, UK, on November 22nd. This is a conference aimed at bringing together and promoting the amazing wealth of local talent and activity in PHP within the North West and wider area. The schedule is online already and tickets are priced at a very reasonable and credit-crunch-friendly £50 (with discounts for students and OAPs) – and all that isn’t enough to persuade you, remember I’ll be there on the day too :)

Schedule for PHPNW

Today saw the publication of the schedule for the PHP North West Conference – you can see it in full on their site. There are some great speakers lined up – Johannes Schlüter, Rob Allen and Stefan Koopmanschap to name just a few that immediately jump out of the page. Tickets aren’t on sale yet but will be in the next week or so – I know I won’t be missing out on this event :)

Excitement at Ibuildings

I didn’t post much of a wrap-up after ZendCon – partly because that trip ran into the start of another one and I only got home properly yesterday, and partly because something happened in California that I couldn’t talk about until now. One thing I did want to mention is that I gave a session in the unconference while I was there. I spoke jointly with Matthew Weier O’Phinney – despite any previous panicking I may have done about talks, I had very few nerves this time around and really came away feeling quite inspired about speaking in general. We signed up for the slot the day before (many thanks to whichever people were involved in conspiring to get me to do this), put a few slides together over breakfast, and took it from there with surprisingly good results.


(this is us drinking, rather than speaking, obviously)

Back to my ZendCon story. A few weeks ago, my employers Ibuildings announced their PHP Centre of Expertise which we will be building up. Its an initiative to support the wider PHP ecosystem, particularly because so many key PHP community people and contributors are employed at Ibuildings. I’m not usually a big fan of towing the company line on personal blogs, but this story is important to me.

ZendCon finished on the Thursday lunchtime and after a long afternoon hanging around outside and acquiring some really impressive sunburn (English complexion, Californian sunshine, yes I know I should know better!), the Ibuildings people present at ZendCon went out for a meal – with the table booked for one extra person. When Cal Evans walked in the room, I was delighted to see him, and wondered for a moment if he had just popped in for some beer and chatter – but I was completely and wonderfully wrong! Cal is the Chair of the PCE – so he’ll be my colleague within a few weeks!! I have known Cal for perhaps two years now, he’s a great supporter of phpwomen.org and I count him among my personal friends. Having him move halfway round the world to work with Ibuildings on such an exciting project makes me very optimistic at the thought of things to come. This is Cal and I at the conference:

Ibuildings is often recruiting, and it seems like many friends have joined the organisation already. Could anyone looking for a job with Ibuildings please note that we do have a bonus for employees recommending friends … ?

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!!

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.