Lamplight php client classes


The php client classes provide a simple, object-oriented client which you may use to access the Lamplight API. The client uses some components from the Zend Framework library (Zend_Registry, Zend_Validate, Zend_Http, Zend_Uri, Zend_Loader, Zend_Json and Zend_Exception). These can be downloaded from the Zend Framework website. The client library requires php 5. Zend Framework is licensed under the New BSD Licence; the Lamplight client classes are licensed under the BSD licence.

To use the client you will need to add the Zend framework and Lamplight client files to your server, and make sure they are accessible in your include path.

You can view the full API documents here. You may also find the Zend Framework API documentation useful. Some basic examples of usage are shown below; the examples also use the client classes.


  1. Overview - how the Lamplight_Client works in general terms
  2. Setting up the client
  3. Getting data from Lamplight
    1. Specifying the type of data and request
    2. Specifying additional parameters
    3. Making the request
    4. Using Lamplight_RecordSet and render templates
    5. Using custom renderers
  4. Sending data to Lamplight
    1. Sending data: attending a work record
    2. Sending data: getting the response
    3. Adding attendance to several work records and handling the response
    4. Accepting referrals through the API
    5. Adding and editing profiles
  5. Handling errors

Overview - how the Lamplight_Client works in general terms

The Lamplight_Client class has been written to make it easier to use the API, without needing to construct URLs and make all the calls to the server. Lamplight_Client extends Zend_Http_Client, adding specific methods for use with the the Lamplight API, but you shouldn't need to worry about the Zend documentation to get started - use the examples and methods documented on this site to get started.

In broad terms, in your php script you will need to:

  1. Instantiate a Lamplight_Client with your API access credentials:
    $client = new Lamplight_Client('', $credentials); 
  2. Specify the data you want:
  3. Make the request:
    $response = $client->request();
    This is making an HTTP request to the Lamplight server for the data requested. The client returns a Zend_Http_Response object which will contain the data (or errors) from the request.
  4. Get the data:
                    $data = json_decode($response->getBody());
    The body of the response contains the data returned by the server, as a json string. We decode it into a php stdClass object to access the data...
  5. Show it:
                    foreach ($data as $rec) {
                        // Display it as you want it: 
                        echo html_entities($rec->name, ENT_QUOTES, "UTF-8");
    The Lamplight_Client has some nice ways to render lists of data using templates.

This is a very simple overview: real examples will need to pass additional parameters (which organisations do you want to see?), and you have complete control over how it is displayed.

You can, of course, re-use the Lamplight_Client in the same script, but if you do you will need to reset it first. So:

  1. Do something else - let's fetch a work record:

If you do not reset the client you will get an error message (probably code 1006).

Example 1: Setting up the client

You will need your API credentials: these can be passed in the constructor to the Lamplight_Client or separately with the setApiParamter($field, $value) method.

   * Include file defines constants:
  require_once '';
  require_once 'Lamplight/Client.php';
   * Set up the new Http_Client
  $client = new Lamplight_Client('', array(
     'key'     => LAMPLIGHT_APIKEY,
     'lampid'  => LAMPLIGHT_ID,
     'project' => LAMPLIGHT_PROJECT

The client instance is now ready to start using. It will use a GET request when requesting data, and a POST request when sending it using the datain modules. If you wish to set additional parameters manually you will need to use setParameterGet(field, value) or setParameterPost(field, value) as appropriate.

Example 2: Specifying the type of data and request

You need to tell the client what kind of data (people, organisations, work or workarea) you want, and how you want to make the request - retrieve all, some, or one. Retrieving one requires an id; but also provides a lot more information about the record.

Lamplight_Client gives some convenience methods to do this. It also provides a fluent interface, so that you can write your code in sentences.

// we want some organisations (that are 'users' in Lamplight)

// or do we want all workareas (order doesn't matter):

// or do we want one work record 
// (we already know the id of a publishable work record)

Of course, each request can only do one thing, so you'd only specify the kind of data and type of request once.

Example 3: Specifying additional parameters

Some requests will require (or want) additional parameters. A common use might be work records in the next month, so we need to set 'after' and 'before' parameters:

$today     = date('Y-m-d');
$nextMonth = date('Y-m-d', strtotime('+1 month'));

$client->setParameterGet('after', $today)
       ->setParameterGet('before', $nextMonth);

Example 4: Making the request

To send the request to the Lamplight servers, use the request() method:

$response = $client->request();

The response object returned is a Zend_Http_Response. However, you may not need it, depending on your usage.

Example 5: Using Lamplight_RecordSet and render templates

Lamplight_Client comes with some sugar: a getRecordSet() method. This will build a Lamplight_RecordSet instance for you, containing some Lamplight_Record_* instances, one for each record returned. Both Lamplight_RecordSet and Lamplight_Record_* classes implement Iterator, so you can loop through them easily.

You may not need to, however; Lamplight_RecordSet provides a render($template) method which uses a simple template string with placeholders for field values.

So continuing from Examples 3 and 4, we know we will have a Lamplight_RecordSet full of Lamplight_Record_WorkSummary instances. Each record will have id, title, workarea, start_date and end_date fields. We can render a simple list of these using the render template:

$recset = $client->getRecordSet();

$recordTemplate = '<li><h4>{title}</h4>'
     . '<i>Start date:</i> {start_date} <br/>'
     . '<i>End date:</i> {end_date} <br/>'
     . '<a href="workdetail.php?id={id}" title="see more info on {title}">'
     . 'more...</a>'
     . '</li>';
echo '<ul>' . $recset->render($recordTemplate)  . '</ul>';

Which will render an unordered list of all the records in the set.

Placeholders are field names enclosed by curly braces {}.

Example 6: Using custom renderers

The problem with the example above is that the dates will be rendered in the format they come from the server: YYYY-MM-DD hh:ii:ss format (e.g. 2010-10-23 10:30:00), which is not particularly reader-friendly. To customise the way in which particular fields are rendered, you can use your own Record classes, or implement the classes provided, which only extend Lamplight_Record_Abstract without adding any methods/properties. Each Lamplight_Record_* class extends Lamplight_Record_Abstract. To use your own class, extend the abstract class (or even the concrete class, if you like) and implement a renderField() method:

// This must be saved as My/Record/WorkSummary.php and be include-able

class My_Record_WorkSummary extends Lamplight_Record_Abstract {

  public function renderField($field) {
    $val = $this->get($field);
    // date fields get rendered differently:
    if ($field == 'start_date' || $field == 'end_date') {
      return date('H:i, d/m/Y', strtotime($val));
    // otherwise use the default renderer:
    return parent::renderField($field);


and then pass in your class name to getRecordSet():

$recset = $client->getRecordSet('My_Record_WorkSummary');

Your start and end times will now be rendered as 10:30, 23/10/2010. You can see it in action in this example.

Sending data: attending a work record (New in version 1.1)

With the datain modules in Lamplight you can also send data to Lamplight using the API and Lamplight_Client class. Version 1.1 of the Lamplight_Client includes a attendWork method that enables you to take bookings for published work records via the API.

    // $id is the id returned in a request to work/some or work/one
    // The record needs to allow attendees to be added - the boolean
    // may_add_attend field returned tells you this
    $client->attendWork($id, '');


You would then call request() as usual. Lamplight_Client will automatically use a POST request to the Lamplight server. In this case, however, the response is not a set of records, and using Lamplight_RecordSet will not apply. Instead, a new Lamplight_Datain_Response class has been added that wraps the response and provides some convenience methods

Sending data: getting the response

Once you have made the request, you can call getDatainResponse on the client to get the response in an easy-to-handle package

    $response = $client->getDatainResponse();

Note that this will throw an Exception if you try and use it when you've not made a 'datain' request. Some of the useful methods on this class are:

    // Did Lamplight manage the response successfully?
    // This is a Boolean


In the attendWork example, success means that the work record had 'add attendees via the API' enabled, there was space (if a maximum number of spaces had been specified), and that the email address provided was uniquely matched. If any of these conditions are not met, success() will return false. You can then check what went wrong and inform the end user as you see you fit:

    $response->getErrorCode(); // Will be a number
    $response->getErrorMessage(); // Will be a human description.


The core API documentation lists error codes and messages.

Adding attendance to several work records and handling the response

The attendWork() method will also accept a comma-separated list of id's that you wish the attendee to be added to:

    $client->attendWork('123,456,678', '')

    $response = $client->getDatainResponse();

In this case, the response for each record may vary (one may be booked up, while the other two are OK, for example). Lamplight will return a batch of responses, one for each work record. When you call getDatainResponse() the Lamplight_Datain_Response returned will in fact automatically create a set of Lamplight_Datain_Response instances, one for each work record. These are contained within the Lamplight_Datain_Response returned, and you'll need to handle things slightly differently.

    if ($response->success()) {

        // We've added them to all the work records requested
        // successfully.
    } else {

        // At least one of the attendances was unsuccessful

        // Check if it was a 'multiple' request (ie to more than one work record)
        if ($response->isMultiple()) {

            // We can iterate through the responses and check each in turn...
            foreach ($response as $individualResponse) {

                // Was this one OK?
                if ($individualResponse->success()) {
                    // They added OK - inform them...

                } else {
                    // We can get the id of the record from the response.
                    // You could store the work record details
                    // in a session variable earlier on, and use this to
                    // provide a more helpful reply.

                    echo 'We were unable to add you to record id ' . $response->getId();

        } else {
            // It was just one record we were adding them to.  
            // We'd suggest you customise the message
            // a bit, rather than just showing the standard Lamplight error
            echo $response->getErrorMessage();


The key method to check here is isMultiple() - if it is, then we can iterate through using foreach. The ID of the record is added to each response (whether it's a multiple or not) for convenience.

Accepting referrals through the API

The datain module also allows you to accept referrals through the API. In contrast to attendWork(), which requires you to have created a work record within Lamplight, the referrals API will create a new record from scratch through the API. To do so, version 1.1 of the php client code allows you to do so using the Lamplight_Record_Referral class.

    $referral = new Lamplight_Record_Referral();

    // We can set using named setter methods
    // or the generic set() (ends up the same).
    // Setters implement a fluent interface so you can
    // chain them if you want to.

    $referral->setReason("I'd like to access your services")  // reasons are strings
        ->setWorkarea(2)  // workarea should be an int (you may need to cast first)
        ->set("date", "2012-03-01 10:30:00")  // dates need to be in this format
        ->setAttendee("");  // must be email

Once we have our referral, we can use the Lamplight_Client to save the record:


As before we can access the Lamplight_Datain_Response class: from the Client to check if it was successful or not:

    $response = $client->getDatainResponse();

    // A bit brutal, perhaps...
    if ($response->success()) {
        echo 'Referral accepted';
    } else {
        echo 'Referral rejected';

Note: since version 1.2 of the php client library, the class hierarchy for Lamplight_Record_* has been refactored (in backwards-compatible ways). Records that may be mutable (ie records you can change through the API) now extend the abstract Lamplight_Record_Mutable class, which in turn extends Lamplight_Record_Abstract. Methods and properties invovled in changing records are now in this Mutable class.

Adding and editing profiles through the API (New in version 1.2)

Since version 1.2, it is possible to add and edit profiles through the API, and this is supported in the php client. This works in a similar way to the referrals above.

To create a new record, we instantiate a new Lamplight_Record_People or Lamplight_Record_Orgs:

    $rec = new Lamplight_Record_People();

    $rec->set('first_name', 'Thomas')
        ->set('surname', 'Crown')
        ->set('address_line_1', '123 Hat Lane')
        // ... and so on ...
        ->set('A_custom_field_that_may_be_altered', 789);
        // custom fields use underscores between words

We then use the Lamplight_Client to save the new profile to Lamplight:



If successful, the response is an object with the new Lamplight ID. Otherwise, it will be an error response: codes and messages can be found here.

To edit an existing record, you will also need to set the id of the record, along with the data you wish to edit:

    $rec->set('id', 46)
        ->set('email', '');



Lamplight_Client will not load the data first when you set an ID - you will need to do this yourself separately if you need to. An example illustrating this is available here.

Handling errors

It is generally a good idea to wrap all your code in a try/catch block so that any errors can by gracefully handled.

In addition, Lamplight_RecordSet and Lamplight_Datain_Response both provide some convenience methods to access error state information.

// A boolean check for whether there were any errors: true means there were 
// some

// Returns the http response status (i.e. 200, 400, 403)
// 200 OK: the server returned data fine
// 400 BAD REQUEST: there was something wrong with your request query
// 403 NOT AUTHORIZED - there was a problem with your authentication parameters

// Returns an integer error code from Lamplight.
// This means the response was not 200 OK

// Returns an error message string from Lamplight.

See the core API documentation for more details about the error codes and messages that Lamplight may return.