Naneau

Go dik-dik, go!

A book review

It’s been a while since I’ve looked into ExtJS. I used it on a few projects until about a year ago, but due to a switch to Adobe Flex at Angry Bytes I haven’t used it a lot recently. I was contacted by Packt and asked if I’d review a book for them. Sell-out as I am, I said I’d do it. Ext JS 3.0 Cookbook is a programming style cookbook, which means it’s jammed full of “recipes”, that explain how to do various things with ExtJS. For many programming related books I find that style to be simplistic and annoying. As ExtJS can be quite complicated to somebody who hasn’t seen it before, and even the official documentation is a hard read, this book does provide an interesting perspective.

Most common things you’ll run across in the base development for rich internet applications are covered, and then some. It’s a good thing too, because it’s all too easy to get stuck when developing for ExtJS, for javascript novice and experienced programmer alike. For somebody who already knows the ins and outs of ExtJS there’s little added benefit over the manual, but for somebody who needs practical advice in the form of examples ExtJS Cookbook is nice to have around. It does assume a certain knowledge of both javascript and internet development in general though, but as I don’t think complete novices should jump into advanced development anyway, this shouldn’t be a problem.

This book is meant as a reference or composed tutorial, and it’s something you’ll find yourself coming back to during development. I experimented a bit with ExtJS again – just for fun – while reviewing the book. I did find that picking up the book and looking for things make for a much more pleasurable experience. Having a jumping off point did make life easier for me. I hacked together a little database management tool with ease. With the downloadable code you get to the phase where you’re modifying something that works without going through the “what on earth am I supposed to do”-phase, which is all too common with complex frameworks like ExtJS.

That being said, there is definitely no big “depth” in the book. That is of course the point of a “cookbook”, but it does sometimes leave you wondering. There is no mention of back-end technologies for instance. The book uses the often seen Sakila sample database, but it doesn’t tell you how to get that from MySQL to JSON and the browser. There is however a nice “How it works” section with all section. That, for me, made this book interesting enough to keep around while playing. Although they are only short, they just keep you interested enough to keep going, something that I sometimes found hard to do with just the manual.

There’s a good focus on common patterns in the book, and there’s even an entire chapter dedicated to them. I did find this to be a nice thing, as in javascript development there isn’t a whole lot of consensus on patterns. The code in the book is all nicely laid out, and clear and concise. Most of the book is about the creation of certain layouts, grids or forms, which tend to have easy to read code anyway. Not that that makes writing such code any easier of course, but hey, that’s what books are for. Personally I did find that the code could have used some inline comments, but as there is plenty of explanation besides it I can’t say that annoyed me a lot.

In general I liked the book, and the opportunity to look back at ExtJS. Although I have quite a bit of experience developing for ExtJS, I did see explanations and code examples that made things clearer for me. I don’t think I would have looked for this kind of book by myself, but, as said before, for ExtJS it makes a whole lot more sense to me than, say, for PHP or JQuery which tend to be much easier to get your head around by themselves.

Arduino and an I2C temperature sensor

Introduction

(skip this if you just want to know about TC74’s and Arduinos)

The first post of the season will be about my new love. I’ve been hacking software for a looong time now, but the last time I did any serious hardware stuff was back in high school.

And I’m glad to say that I forgot almost everything about it. I seem to remember some guy named Ohm being important, but that’s about it. But, lack of knowledge aside, writing code that, at best, changes a few pixels on a screen is a somewhat limited domain. I wanted to make something cool, something that moves, something interesting.

Arduino to the rescue! are awesome little things that let you play with electronics in a fun and easy way. At it’s heart lies a programmable chip (an ATmega168 to be precise), which you can attach stuff to. All kinds of stuff! There are dozens of examples of stuff being attached to arduinos in order to make them flash, vibrate, move, dance and sing to be found on the web.

And I’m not going to write about flashing leds or controlling servos. I’m going to do something a little bit more complex. I’ve been playing with my arduino for a couple of weeks now (mostly during weekends) and I’ve built a little robot around it (which I’m sure I’ll write about another time). One of the problems you start facing when building large, complicated things, is that you are going to run out of ports to connect stuff to. The currently “standard” Arduino Duemilanove has 13 digital I/O ports, and 5 Analog IN ports. This is plenty for basic sensor input, driving a dc motor through a controller and a few servos on the side (in short, plenty for a robot). But if you want to control a few dozen leds independently you’ll be out of luck.

That’s where buses come in. They allow communication in a standardized form over a smaller number of wires than you would need to attach the components on the bus to your controller separately. I had of course read about them, in some computer science class a couple of years ago, but never used a bus directly. Abstraction layers make your life easier, and I am lazy. I work at least levels above bus level usually.

I2C

The TC74 temperature sensor I hooked up today uses an I2C bus. This bus has been designed here, in the Netherlands, by Philips. It requires only two wires, and has a 7 bit addressing space (if that doesn’t mean much to you, think: “you can hook up a lot of things to just 2 ports on your Arduino”).

Starting out with low-level bus communication for a person like me is… Difficult at best. I spent 2 hours just hooking up a single digital sensor, which would have taken me 5 minutes were it a “normal” analog sensor. You’ll need skills like Binary-To-Hexadecimal conversion and a hacker attitude. You will have to pay closer attention to datasheets than usual, because it’s harder to troubleshoot things when they go wrong. But don’t let that scare you away, there are a lot of benefits to using serial communication with your components, most of all that you need two wires to hook up a whole bunch of stuff.

Arduino has a library for I2C communication, which you can include in your sketch like:

1
2
#include "Wire.h"
//wire library

There is a reference page for the Wire library, but don’t expect too much from it. Wire (why didn’t they just call it I2C?) takes care of some of the communication details, but you will still need to know intimate details of the communication protocol, as it differs from part to part.

The connector layout for a TC74 sensor

Connecting the sensor to the relevant ports is easy enough. There are only 4 wires that matter, there is the standard +5V and GND connectors, which go to the +5V and GND connectors on your arduino (durrr), and then there’s two wires for I2C. One is a clock line (SCL, sometimes written as SCLK), which is controlled by the master (your Arduino), and can be thought of as the rhythm section of an orchestra. Communication is a series (hence “serial communication”) of 1s and 0s, and they are “measured” on each “beat” of the clock line. When using the Wire library, your Analog Input 5 is automagically set up as the SCL line. On a TC74, the second wire from the left is SCL. The other wire in the I2C setup is the data wire (SDA), which is the wire that is either high for 1, or low for 0, synced with the clock.

The difficult part about bus communication is that you need to specify specific addresses for each component added to the bus. These addresses can sometimes be set with control pins, but for the TC74 they are set in the factory. An address is 7 bits long, and for the TC74 the first 4 bits are always 1001. The most common TC74 sensor, the TC74A5 has the address of 1001101 (101 is binary for 5). There’s a whole series of TC74’s, from TC74A0 (address 1001000) to tc74A7 (1001111). Do you see the connection? Well I didn’t, at first. I didn’t realize that my sensor was an A7 model, which led to extreme frustration as I tried to communicate with a non-existent component on the bus.

So how does this communication actually work? Well to start you’ll have to tell the Wire library to set your Arduino up as a bus master:

1
2
3
4
5
6
void setup()
{
  Wire.begin();
  //the begin() method accepts an address parameter
  //but that would make your arduino into a slave
}

Communication is set up into blocks. A master initializes it by writing the address (that’s 7 bits, remember?) of the component it wants to talk to on the SDA line, with the last bit being either 0 for read, or 1 for write. Making it into a block of one byte long. Don’t worry about the read/write stuff, we’ll get to that. In Wire code, beginning a conversation with your TC74 sensor would look like:

1
2
3
4
5
6
7
8
9
10
11
#define address 0x4F
//the address of the sensor, in hex, it's the equivalent of 1001111
//which is the address found in the datasheet of my sensor
//this may seem complicated if you've never seen hex before
//for a TC74A5 it would be 0x4D

void setup()
{
  Wire.beginTransmission(address);
  //start the transmission
}

Now, in the datasheet for your component you’ll find a timing diagram. It specifies what the component expects at certain points during communication. There will be references to “registers” and “commands”. Usually you’ll issue a command to either read or write something from a register. What the component does with the value of a register is of course dependent on what kind of component it is. For our TC74 temperature sensor, you can read a register that contains… The current temperature.

The command to “read” the register is 0×00 (that’s hex), which is found in the datasheet. After that, the datasheet says, you have to repeat the address of the slave in read mode. This means that you put the 7 bits of the address on the SDA line, but with a 1 following it, and not a 0 (which was how beginTransmission() put it on the line). After that we can read the value, which is a single byte with the temperature in Celsius:

1
2
3
4
5
6
7
8
9
10
11
12
  Wire.beginTransmission(address);
  //start the transmission by writing the slave address
  Wire.send(0x00);
  //send the command to read the temperature
  Wire.requestFrom(address, 1);
  //read 1 byte from address
  //this re-broadcasts the address in read-mode
  int temperature;
  if (Wire.available()) {
    //check if we can read
    temperature = Wire.receive();
  }

Now our integer “temperature” holds the current temperature. In theory. If something went wrong it’ll hold 0, which is a valid temperature (a little too cold to be working with small electronic components though ;) ). It would be best to add an else-clause to the if-clause and do something meaningful.

A full sketch that reads the temperature and puts it on the serial line looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "Wire.h"
//wire library

#define address 0x4F
//address of the temperature sensor

#define delayC 1000
//delay count in ms

#define baudrate 9600
//baudrate for communication

void setup()
{
  Wire.begin();
  Serial.begin(baudrate);
}

void loop()
{
  Serial.print("temperature in Celsius: ");
  //let's signal we're about to do something
 
  int temperature;
  //temperature in a byte

  Wire.beginTransmission(address);
  //start the transmission
 
  Wire.send(0x00);
 
  Wire.requestFrom(address, 1);
  if (Wire.available()) {
    temperature = Wire.receive();
    Serial.println(temperature);
  } else {
    Serial.println("---");
  }
 
  Wire.endTransmission();
  //end the transmission
 
  delay(delayC);
}

I hope this was a little helpful to you. I found it a bit hard to start with I2C because of a lack of documents on the web written for noobs like me. If you want to read more, I would suggest the following resources that detail specifically with Arduino’s I2C support:

Reports of my death have been greatly exaggerated

After being tagged by norm2782, I feel compelled to do a little writing myself. I will however break the tagging chain, because I don’t have any friends to tag :( . So let me bring you up to speed. What have I been doing?

Well… Believe it or not. I have a job now! I am working on a ZF and Flex based content management system over at Angry Bytes. I had been doing freelance work there but right now I work there full-time to scrum out this beautiful piece of software (if I say so myself ;) ). I got norm2782 an internship there, so he’s helping me out.

I also have a new hobby! I’ve always have been interested in taking things apart. As a small child I’d destroy things to see how they work and I still do that. Nowadays I do most of my hacking on software, but I decided it was time I did something hardware-ish too for a change. Nerdy as I am, I got myself an arduino board to play with!

I must admit that I have not been doing as much work on Madoqua as I could have been doing. However, there has been some nice community interest and there have been improvements. The alpha is, of course, still a couple of weeks away, like it was 2 months ago :(

Oh well… Let’s see if I can keep it up this time.

Router abuse

Routing?

Today a post about Routing, that’s right, a real new post! How to use routes to get from a (nice looking) URL to modules/controllers/actions is something that has been explained in dept here and at other places. This post is not about that. This post is about how to use the router to reverse the process, to build your own pretty urls. For simplicity’s sake I’m going to assume that you use the router to do just that, parse and create URLs. You could of course use it for other funky things, like parsing CLI input.

The router

The router lives in front-controller-land, you have problably retrieved it before, to add routes to it.

1
2
3
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
//the router, retrieved from the front controller

The router holds a collection of routes, that it tries to match against the current request. You can retrieve one of those routes using the getRoute() method. The method getCurrentRouteName() will give you the name of the current route. Remember when you added routes to it you had to give them a name? That is going to come in useful now. If you didn’t add any routes to the router, or aren’t using any special route, the name of the route will be “default”, seeing as how that is… The default.

1
2
3
4
5
$currentRoute = $router->getCurrentRouteName();
//get the current route name

$route = $router->getRoute($currentRoute);
//get the actual route object matching the current name

Assembling routes

While getting a route is fun, it doesn’t do you any good unless you put that route to work. Which is what we’re going to do next! The assemble() method has to be defined by all classes that implement Zend_Controller_Router_Route_Interface (along with the match() method that does the matching of the request). Like it’s name suggests, it is supposed to assemble a url for a given request. It takes an array of parameters as the first param, and an optional boolean as a second, to reset the current request params for assembling.

1
2
3
4
5
6
7
8
9
10
$params = array(
    'module' => 'blog',
    'controller' => 'post',
    'action' => 'read'
    'id' => 13
);
$route = $router->getRoute('default');
$url = $route->assemble($params, true);
//create a url using just the params set in $params
//this will look like blog/post/read/id/13

This is also useful, however, when you don’t use the default route:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$router->addRoute(
    'post_read',
    new Zend_Controller_Router_Route(
        'post/:id',
        array(
            'action' => 'read',
            'controller' => 'post',
            'module' => 'blog',
        )
    )
);
//add a route for purrrty urls

$router->getRoute('post_read');
$url = $route->assemble(array('id' => 13), true);
//$url will be post/13

Why do it yourself?

Yes, I am acutely aware that most scenarios for when you’d want to do this are covered. For controllers there’s the redirection action helper, which uses this method to generate it’s urls. For views there’s the url view helper, which helps you generates links to put in your hrefs. But there are places where you don’t have the benefit of these helpers (without hackisly using them out of context). For instaces, generating actions for forms can’t be done automatically (yet). So, why not add a little method to your form?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * set the action based on a route
 *
 * @param array $params
 * @param string $routeName
 * @param bool $reset
 */

public function setRouteAction($params = array(), $routeName = null, $reset = false)
{
    $frontController = Zend_Controller_Front::getInstance();
    //the FC
   
    $router = $frontController->getRouter();
    //the router (assumes rewrite router)

    if ($reset) {
        $routeName = 'default';
    }
    //hmm... this may lead to unexpected results
    //but so will getting the current route name
       
    if ($routeName == null) {
        try {
            $routeName = $router->getCurrentRouteName();
        } catch (Zend_Controller_Router_Exception $e) {
            $routeName = 'default';
        }
    }
    //requested routename/default
   
    $route = $router->getRoute($routeName);
    //the current route
   
    $action = rtrim($frontController->getBaseUrl(), '/') . '/';
    $action .= $route->assemble($params, $reset);
   
    $this->setAction($action);
}

I’m Back!

Hey loyal horde of fans. Stop your e-mailing and other forms of poking, I am back! I have had a bit of a weird half year, that has kept me from blogging. But that is about to change. I have a few nice blog posts lined up for you in the *near* future.

Being out of the loop for a while has weird effects on a code junkie. I haven’t had much time to keep up with the ever ongoing development of the Zend Framework I have written so much about in the past. I pretty much missed the 1.5 release and have only recently started to play with the framework again.

I also have a nice little surprise in store for you. It’s called Project Madoqua, and there will be more information soon, I promise.

Well, I look forward to blogging for you all again. See you soon with a more… Informative post!

Madoqua.org

Fun with the ViewRenderer

The ViewRenderer

Really, there is fun to be had! Since it’s introduction, the ViewRenderer had caused headaches and frustration. It is the one thing that glues the Controller and View parts of Zend’s MVC implementation together. As such, it ties in strongly with your code and is likely to cause confusion if you don’t know what it does.

Retrieving the helper

The ViewRenderer is an action helper. This means that it is stored in the helper broker. You can retrieve it anywhere in your code with:

1
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');

There is one small catch. If you retrieve it before dispatch, the view object it contains has not been initialized. You can do that yourself by calling initView() on the object:

1
2
3
4
5
6
7
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->initView();
//retrieve the helper and initialize the view

$viewRenderer->view->someVar = 'someValue';
//set a variable in the view
//this will be available in all your view scripts

The view object contained in the helper is the only view object your application will work with. Any variable you assign to it will be available in all the view scripts you render. If you want to modify the view script, for instance if you want to pass extra configuration options, you can do it like this:

1
2
3
4
$view = new Zend_View(array('encoding' => 'utf-8'));
//a view object with the encoding option set to utf-8
$viewRenderer->setView($view);
//set the object in the viewRenderer

In this example, all I do is set up a configuration setting. As is made clear in the comments for this post, this could also be done with:

1
$viewRenderer->view->setEncoding(’utf-8′);

If you want to use a custom view object, like one with Smarty rendering, you do need to set up the property yourself.

Setting up your view scripts

Unless you disable it, the ViewRenderer action helper will try to render a view for every action that gets called. I am sure that by now you know that for a controller FruitController, with an action appleAction() you need to create a view file “/views/scripts/fruit/apple.phtml”. View scripts are stored in the “views” directory of your module. If you use a directory layout without modules (i.e. you only have a single non-namespaced module “default”) you should have it in the same directory as you “controllers” directory.

You can immediately see the problem here. If you don’t follow the convention for naming your view scripts you get an exception like:

1
script 'index/index.phtml' not found in path (/your/path/to/view/scripts/)

The assumption that every action will have a view may be false for you. Luckily, the helper is smart enough to not try to render a view when you do _forward() and _redirect(). If you render a view manually (using $this->render()) it won’t try to find the default view either. If that is not enough for you, you can disable the view rendering for a specific action with:

1
2
$this->_helper->viewRenderer->setNoRender();
//disable the view rendering for an action

Advanced ViewRenderer magic

When you start writing view helpers you’ll probably put them in the “helpers” subdirectory of your “views” directory. This is fine, but it will start causing problems as soon as you want to use the same helper in other modules. To get around this you could put the helpers in your library and add the containing directory like this:

1
2
3
4
5
6
$viewRenderer->view->addHelperPath(
'Naneau/View/Helper/',
//the path to the helpers
'Naneau_View_Helper'
//the class prefix
);

As you can see, the addHelperPath function of Zend_View expects two arguments, one is the path to where your helpers are located. The second is the prefix for the helpers. I use “Naneau” as my namespace, so my helpers start with Naneau_View_Helper.

Another thing that people regularly ask is how to put the content the helper renders into a sidewide layout file. There are several solutions for this. The most interesting at the moment is called Xend_Layout. It will, in modified form, be included in the 1.1 release of the framework as Zend_Layout. SpotSec has written a nice article about it, which I suggest you read ;) . Just remember that even advanced solutions like Xend_Layout use the ViewRenderer. Also, please note that Xend_Layout is currently a proposal, and is likely to undergo significant changes before it moves to Zend_Layout.

ZFQuotes, part one

Today I have a short, but interesting post for you. Over time I have remembered some of the more interesting people have said about the Zend Framework. Sometimes I was even smart enough to log them to a file.

So, I present to you “ZFQuotes, part one”:

<andrewtaylor_> It’s weird, working with the framework, you have to go back and question the way you’ve done everything in the past

<SpotSec_> while Zend Framework does make things easier, I find that many people who just dive into using a framework before they learn how the framework works tend to run into a lot of simple problems ;)

<cyth> I know i will get flaimed for this
<cyth> but the best way to understand ZF is to learn RoR

<StormTide> a framework without a layout or form solution…

<SpotSec> SpotSec’s Law states that the more users = the more idiots = the more bad code = cakephp

The magic of view helpers

It has been a while since I’ve written on my blog, so it’s about time I give you all an update. I thought I’d start with something fun: view helpers.

Even for those of you who don’t always find joy in programming, view helpers might just make you happy. They can really make some of the more annoying tasks, like the ones where you have to switch in and out of PHP context, a lot easier.

In it’s most basic form a view helper looks like this:

1
2
3
4
5
class Naneau_View_Helper_SomeHelperName {
     public function someHelperName() {
          return 'Hello, cruel world!';
     }
}

As you an see, the class does not have to extend any base class, like action helpers and plugins do. There’s just one public function in there, which shares the name of the class (except it’s first letter isn’t capitalized). When the helper gets called from your view, an object of this class gets initialized, and the function is executed.

That’s all there is to it. You write a small class, and put a single function in there, it couldn’t be any easier. From your view you can call it like:

1
2
3
4
5
6
<?php
echo $this->someHelperName();
//creates object of class Naneau_View_Helper_SomeHelperName
//calls function someHelperName()
//echos result 'Hello, cruel world!'
?>

Now, while single function view helpers can help you avoid a lot of repetition and ugly mixed php/html code, there is a limit to what you can do with just one function. Sometimes you just want to add more logic to your class. For instance, say that you want to count something, and display the result. You would want to have a method for adding, and a method for displaying the result. There is a neat little trick to accomplish this using view helpers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Naneau_View_Helper_CounterHelper {
     /**
      * a counter
      * @var int
      */

     private $_counter = 0;

     /**
      * get the helper instance
      * @return Naneau_View_Helper_CounterHelper
      */

     public function counterHelper() {
          return $this;
          //return this object (for chaining)
     }
     
     /**
      * add to the counter
      * @param int $howMuch
      * @return void
      */

     public function add($howMuch = 1) {
         $this->_counter += $howMuch;
     }
     
     /**
      * get the result
      * @return int
      */

     public function result() {
         return $this->_counter;
     }
}

If you look at the “original” helper method “counterHelper()”, you can see that it returns $this. This allows you to chain the result to other methods in your view:

1
2
3
4
5
6
7
8
9
.. this is a view ...
<?php $this->counterHelper()->add(1); ?>
... view stuff here ...
<?php $this->counterHelper()->add(2); ?>
... some more view stuff ...
<?php
echo $this->counterHelper()->result();
//will output 3
?>

Now, there is one more thing you should know about view helpers. Sometimes you want to call one helper from another. This is possible by accessing the view object the helpers work on. As soon as you call a view helper from a view, it tries to call setView() on the helper, passing itself (the current view object) as a parameter. This means you can retrieve that object by adding the method to your helper:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Naneau_View_Helper_Composed {
    /**
     * the view object
     * @var Zend_View
     */

    private $_view;
   
    /**
     * set the current view
     * @param Zend_View $view
     */

    public function setView($view) {
        $this->_view = $view;
    }
   
    /**
     * the main helper method, uses the counter helper
     * @return int
     */

    public function composed() {
        $this->_view->counterHelper()->add(10);
        $this->_view->counterHelper()->add(5);
        //assume this is something useful ;)
        return $this->_view->counterHelper()->result();
    }
}

Which you could use like:

1
2
3
4
<?php
echo $this->composed();
//will output 15
?>

Working on the wiki

Last night, SpotSec and I had the great idea of starting a little knowledge base for the Zend Framework. We have both noticed a number of frequent problems people (not just noobs) run into while trying to use the framework. While we intend to set up a proper knowledge base later (probably building some kind of website for it, seeing as we’re such nerds ;) ) we have started with a simple Wiki page.

This blog post is merely a cry for help. While we’ve covered the basics, there must be more problems out there that we’re forgetting. If you have some kind of issue that you keep running into, let us know. Or even better, edit the wiki page! Go web 2.0!

Oh, and we know the wiki has been down a lot in the past. It seems to be running fine now, but I can’t guarantee it will keep doing that of course :)

Update

It appears the whole knowledge base idea has already been copyrighted by mirmo ©. Oh well… We’ll let him do all the work!

In all honesty, mirmo is a great guy, and he did help think this up. So kudos to him!

Use the URL view helper, please

When writing views, some time sooner or later, you’re going to be creating links to your own pages. Because you don’t want to end up writing relative URLs (they will not work, because the browser will add them to the current path), you need to have some kind of a base URL. A lot of people start writing links like:

1
<a href="/my_app/user/edit/id/123/">click me!</a>

While they will function perfectly, there’s two problems, both related to manageability of your website. First is that if your base URL changes (the “/my_app/”), you will have to edit all of your views. Second is that if you use custom routes you may end up with outdated routes, or even worse, erroneous routes in your views. Again, this would mean that you’d have to edit your view scripts.

There is a (near-) perfect solution for this, in the form of a view helper. The URL view helper will create URLs for you, based on your custom routes, and using the base URL set in your front controller. So, the first example could be written as:

1
2
3
4
5
6
<a href="<?php echo $this->url(array(
'controller' => 'user',
'action' => 'edit',
'id' => '123'
));?>">click me!</a>
//line endings added for readability

Say, if you were to add a custom route like so:

1
2
3
4
5
6
7
8
$route = new Zend_Controller_Router_Route(
    'edit/:id',
    array(
        'controller' => 'user',
        'action'     => 'edit'
    )
);
$router->addRoute('userEdit', $route);

The view helper could generate a matching URL for that route. You do however have to tell the helper that you want to use that specific route (which is identified with “userEdit”):

1
2
3
4
<a href="<?php echo $this->url(array(
'id' => '123'
), 'userEdit');?>">click me!</a>
//note the second parameter for the helper

Static files

Now, this will work for all your actions, but there’s still the matter of static files, like images and javascript. If you want your application to be truly portable, I suggest writing a little view helper for static files. I personally use this one, which does nothing but add the base URL to a filename:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
/**
 * StaticFile.php
 *
 * @category   Naneau
 * @package    Naneau_View_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 * @version    0.1.1
 */


/**
 * Naneau_View_Helper_StaticFile
 *
 * a view helper for static files
 *
 * @category   Naneau
 * @package    Naneau_View_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */

class Naneau_View_Helper_StaticFile {
   
    /**
     * get a link to a static file with the current baseUrl
     *
     * @param string $file
     * @return string
     */

    public function staticFile($file) {
        $file = trim($file);
        //trim the file name (just in case)
        $frontController = Zend_Controller_Front::getInstance();
        //front controller
        $baseUrl = $frontController->getBaseUrl();
        //base url for this application
        return $baseUrl . '/' . $file;
        //the link to the file, relative to the base url
    }
}

In your view scripts you could use that helper to create links to static files:

1
<link rel="stylesheet" type="text/css" href="<?php echo $this->staticFile('blah.css'); ?>" />

Alternatively, you can set a variable to your views that holds the base URL. You would then manually create your links. I personally tend to favor the previous approach, because it allows for less repetition, which is always good. You could for instance set such a variable in your bootstrap:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
//view renderer (from the helper broker)
if (is_null($viewRenderer->view)) {
    $viewRenderer->init();
    //force instantiation of the view
}

$frontController = Zend_Controller_Front::getInstance();
//frontcontroller

//... additional front controller setup goes here ...

$frontController->setBaseUrl('/my_app');
//set your base URL here

$viewRenderer->view->baseUrl = $frontController->getBaseUrl();
//set baseUrl for views, retrieved from the front controller

$response = $frontController->dispatch();
//do... something!

Module-based error handling

Just a short post today. #zftalk is a good source of inspiration for me. Today Dan asked if it was possible to make the error handler use an ErrorController based on the module the error occurred in. There are some good reasons for why you would want this. For instance, your module may raise errors that are specific to it’s environment, and therefore can be handled better in it’s own error handling controller. On the other hand, it will add complexity to your application, and, in the case of an error, complexity is the last thing you want.

At any rate, the most basic approach to make a module have it’s own ErrorController would be like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * init hook, gets executed before any action is dispatched
 */

public function init() {
   
    $front = Zend_Controller_Front::getInstance();
    $errorHandler = $front->getPlugin('Zend_Controller_Plugin_ErrorHandler');
    //the error handler plugin
    $moduleName = $this->getRequest()->getModuleName();
    //module name
    $errorHandler->setErrorHandlerModule($moduleName);
    //set the current module as the error handler module
}

At controller initialization, you retrieve the error handler from the front controller and tell it to use a specific module (the current module) for it’s error controller. This is a foolproof way of doing it. You may also automate this by subclassing the error handler plugin, or write a small plugin to do this for all controllers. But hey, this is fool-proof! ;)

Timing your scripts

We all have to optimize, sometimes. Most people hate it, and for good reasons. There’s a real trade-off between code readability and clarity versus optimization. To get information on how your scripts are performing you’ll need to run software like xdebug. That works fine, especially during development.

But sometimes you just want some quick info on how your site is doing. Especially if the code has already been deployed. I often add a little HTML comment to all my pages with the current execution time. It’s by no means a full profiling method, it’s a quick reference that often gives some confirmation if you think something is wrong.

Today I’m going to show you how to do this with the Zend Framework. I have neglected my blog for too long now ;)

1
2
$timeStart = microtime(true);
//ready, set, go!

You need to get a reference point, so on the top of your bootstrap file you have to get the current time in microseconds as a floating point value (that’s what the “true” parameter does).

Now, you must make sure your application can use this value. I personally prefer setting it as a front controller parameter. Like this:

1
2
$frontController->setParam('timeStart', $timeStart);
//the time we started this request

Now, this is where it gets a little complex. See, you only want to add the execution time to HTML output. What I do to achieve this is use a simple plugin (for the front controller). It will check viewRenderer, to see if it is set to render, then append the execution time tot the body of the response.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
 * ExecutionTime.php
 *
 * @category   Naneau
 * @package    Naneau_Plugin
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 * @version    0.2
 */


/** base class */
require_once 'Zend/Controller/Plugin/Abstract.php';

/**
 * Naneau_Controller_Plugin_ExecutionTime
 *
 * a simple plugin to add the current execution time to html pages
 *
 * @category   Naneau
 * @package    Naneau_Plugin
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */

class Naneau_Controller_Plugin_ExecutionTime extends Zend_Controller_Plugin_Abstract {
   
    /**
     * dispatchLoopShutdown hook
     *
     * runs after all controller actions have finished. appends execution time
     *
     * @return void
     */

    public function dispatchLoopShutdown() {
        $viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');
        //view renderer action helper
        if (!$viewRenderer->getNeverRender()) {
            //viewRenderer is set to render (assuming HTML output)

            $front = Zend_Controller_Front::getInstance();
            //the front controller
            if ($startTime = $front->getParam('timeStart')) {
                //the parameter was set (yay!)
                $totalTime = microtime(true) - $startTime;
                //calculate the time difference
                $this->getResponse()->appendBody("\n<!-- total execution time: $totalTime . //-->");
                //append a comment to the HTML body
            }
        }
    }
}

It can of course be registered with the front controller like so:

1
2
$frontController->registerPlugin(new Naneau_Controller_Plugin_ExecutionTime());
//execution time

Make sure it’s the last plugin registered, otherwise other things will get executed after it, and that may influence the execution time.

Lorem ipsum view helper

A while ago I wrote a little lorem ipsum class. I use it a lot when creating mock-ups. Having realistic filler text really helps with visualizing things.

When I wrote about view helpers the other day it dawned on me that I’ve never posted the view helper I created for use with the lorem ipsum class. It’s the perfect thing to wrap in a view helper. It’s something you’d use in your views, and you don’t want to write the code to use the class directly into your views. Really, you don’t ;)

Anyway, here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
/**
 * LoremIpsum.php
 *
 * @category   Naneau
 * @package    Naneau_View_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 * @version    0.1
 */


require_once 'Naneau/Text/Filler.php';

/**
 * Naneau_View_Helper_LoremIpsum
 *
 * get a number of lorem ipsum paragraphs (random filler text)
 *
 * @category   Naneau
 * @package    Naneau_View_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */

class Naneau_View_Helper_LoremIpsum {
    public function loremIpsum($count = 2, $html = true) {
        return Naneau_Text_Filler::getParagraphs($count, $html);
    }
}

Use it like this (in your view scripts):

1
<?php echo $this->loremIpsum(5); /* 5 paragraphs */ ?>

You have to have the original class in your library, though.

Helpers and plugins

For people new to the Zend Framework the way it implements the model view controller (MVC) pattern may be a bit confusing. While the basic structure couldn’t be easier, it’s the details that cause problems. I’m going to have a go at trying to explain some of them here. I hope it helps. If it doesn’t, blame SpotSec ;) !

Assuming you’re at least somewhat familiar with the concept of MVC, there is Zend_Db_Table for your models, Zend_View for your views, and Zend_Controller_Action to glue them together. Those are the 3 basic classes you’ll find yourself working with over and over again. Worthy of mention is also Zend_Controller_Front, which dispatches an action controller after it interprets a request in your bootstrap file.

If you understand the basics of how the front controller, and it’s default router, work, it’s easy to set up some action controllers, let them render a view and build basic applications. While you don’t necessarily need them, there are additions to the 3 big components of the framework’s MVC implementation that can make your life a little easier.

View Helpers

As soon as you start writing views that consist of more than just text and a little dressing HTML, you’re going to run into view helpers. The framework comes with a set of handy helpers, that you may already use. But what exactly are those helpers, and why should you write one?

Basically a view helper does what it’s name suggests. It’s something that helps you write views. For instance, in the default set of helpers there are helpers that generate form elements and urls. If you find yourself writing the same bit of HTML over and over again in your views, why not build a helper for it? They are very easy to create, consisting of nothing more than a class and a single method.

From view context you can call them using:

1
<?php echo $this->aViewHelper($someVar, $anotherVar); ?>

Where the helper is nothing more than:

1
2
3
4
5
class Naneau_View_Helper_AViewHelper {
    function aViewHelper($someVar, $anotherVar) {
         return '<strong>' . $someVar . '</strong><em>' . $anotherVar . '</em>';
    }
}

Action Helpers

What a view helper is for views, an action helper is for action controllers. They are a bit more complex, but very powerful. If you’ve been around long enough to remember the introduction of the infamous viewRenderer, you already have experience with action helpers. They can perform tasks your controller actions do, and help avoid repetition of mundane controller tasks.

They are more complex than view helpers, because they work with a concept of “hooks”. A hook is a method you can write into your action helpers that gets called at specific moment in a controller’s life cycle. As you may or may not know, an action controller gets instantiated by the front controller and the method matching the action from the request will be called. An action helper has hooks for three moments during that cycle.

There’s init(), which gets called by the helper broker before the controller is instantiated, preDispatch() and postDispatch(), which are called before and after the action method of the controller is called, respectively. From action helper context you can do everything you can do from controller context, including modifying the request and response. You can also retrieve the controller object that you are “helping”, and work with that.

In your controllers all the helpers currently registered are in the $this->_helper array. The viewRenderer action helper, for instance, can be found in $this->_helper->viewRenderer. Action helpers can be set up in your bootstrap using the action helper broker.

For instance, say that you have some variables Foo and Bar, that you want to be available in all your action controllers. For instance, a database connection or the current user would be things you would want access to at all times. You could write a simple action helper that does this:

1
2
3
4
5
6
7
8
9
10
class Naneau_Controller_Action_Helper_FooBar  extends Zend_Controller_Action_Helper_Abstract {
    public function preDispatch() {
        //get $foo and $bar
        //think Zend_Registry
        $controller = $this->getActionController();
        //the current action controller
        $controller->foo = $foo;
        $controller->bar = $bar;
    }
}

In controller context, you could then retrieve them with:

1
2
3
4
$this->foo;
//$foo
$this->bar;
//$bar

Front Controller Plugins

If you find your action helpers lack power, there’s always the option of writing a front controller plugin. They have the same preDispatch() and postDispatch() methods an action helper has, although you can’t modify the action controller directly from a plugin. In addition to those it provides you with a few other “hooks”.

routeStartup() and routeShutdown() are called before and after the front controller starts evaluating it’s request and start looking for routes that match it. dispatchLoopStartup() and dispatchLoopShutdown() give you access to the point in the lifecycle of the front controller where it starts dispatching controllers, and when it stops dispatching them. There’s a subtle difference with preDispatch() and postDispatch(), because those will be called before every single controller action is dispatched.

While plugins are the most scary looking of the three, they are the most powerful. They have the power of stopping a dispatch, so they can be used for access control. Also, if you must insert some variables into the request before anything happens, they are the way to go. Don’t be scared by it’s apparent complexity though, once you get the hang of it you’ll love the control they give you.

If you’d want to force people to log in before they can view your pages, it would make sense to write a plugin for that. Repeating the check for a valid login in every action controller would lead to a lot of repetition. A simple plugin that would check for a login could look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Naneau_Plugin_CheckLogin extends Zend_Controller_Plugin_Abstract {
    public function preDispatch() {
        $login = false;
        //you will probably want to implement this ;)
        if (!$login) {
            //no login
            $request = $this->getRequest();
            //the request
            $request->setModuleName('default');
            $request->setControllerName('login');
            $request->setActionName('index');
            //send to default/login/index
        }
    }
}

View helpers

Another post on views today. But this will be a short one. See, I believe not enough focus is put on the usefulness of view helpers. When trying to separate design from logic, I believe that all things that can be removed from a view should be.

View helpers can come in quite nicely there. Say for instance that you have a Zend_Db_Table_Row assigned to your view, but you want to see the “next” item from the database. Maybe you want to do simple pagination, or maybe you just want to provide some kind of link. A simple view helper for such a situation would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Naneau_View_Helper_Next
 *
 * find the next item for a Zend_Db_Table_Row object
 *
 * @category   Naneau
 * @package    Naneau_View_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */

class Naneau_View_Helper_Next {

    /**
     * find the next item
     *
     * @param Zend_Db_Table_Row $row the row
     * @param string $order what to order it by
     * @return Zend_Db_Table_Row|bool
     */

    public function next($row, $order = 'id') {
        $table = $row->getTable();
        $rowset = $table->fetchAll($order . ' > ' . $row->$order, $order . ' ASC', 1);
        if ($rowset->valid()) {
            return $rowset->current();
        }
        return false;
    }
}

You could call it from view context with:

1
<?php $next = $this->next($someRow); ?>

or if you’d just wanted to echo the “title” attribute of the next row:

1
<?php echo $this->next($someRow)->title; ?>

If you would try to fetch the row yourself from within view context you would put logic in your view that shouldn’t be there. Also, there would be a high risk of repetition and loss of readability.

Of course, you could just assign the “next” row from your controller. If you are sure that the view will need it, this would be the best way. But in many cases, the border of what’s supposed to happen in a controller and what should happen in a view helper is a bit vague. View helpers give more control to the designer of your views, while leaving the back-end code safely in your own hands.

Writing view scripts

A substantial part of my time I spend looking at other people’s code, for various reasons. Sometimes it’s just to figure out how others have solved a problem I am facing, and other times I’m trying to figure out why something doesn’t work. There has a growing focus on coding standards for a while now, and people are even adhering to them ;) .

Modern editing software will auto-indent your code, put a docblock in front of your functions, and do a lot of other useful things that make your code easier to read. But there is one area that is often overlooked: templates. Whether you use a “real” templating engine, or just mix blocks with html, templates have a tendency of getting messy.

When I started this blog, a few months ago now, I thought it would be nice if I created my own wordpress theme. I started out by looking at other people’s themes, and tried to edit them, this proved to be difficult. It shouldn’t have to be that hard. By using just a few rules, your code will be easier to read, and therefore easier to maintain.

A few simple rules

For instance, when using PHP in your templates/views, use the alternative syntax for control structures. Brackets really lose their meaning after ten lines of HTML, and you can’t tell the closing bracket from an if-statement apart from the closing bracket of a foreach-statement.

Also, indentation matters. It matters a lot. I don’t care how you indent, really, but please, be consistent. Either let your control structures define indentation, or let the HTML be boss, just don’t let them both indent. Personally, I only indent HTML, and make the control structures match the level they output. This is counter-intuitive for someone with a coding background, and took me a while before I got used to it. The point it is that you can immediately see the resulting HTML from looking at the code that produces it. Spotting missing closing tags, and other common problems, gets easier.

One of the reasons you write templates and/or view scripts is to separate logic from design. Especially those of us with a bit of experience in writing code, sometimes find it hard to get rid of all logic. I force myself to put all “code” on a single line, unless I really can’t. Even though it may not guarantee a complete separation, I find it difficult to define any real logic on only one line ;) .

Example

As a simple example I have put together a foreach-loop for which the output depends on a variable ($someCondition). It’s a common situation, that I’m sure you’ve seen before. The HTML output is an unordered list, with a paragraph inside the list elements.

Regular syntax with brackets and indentation over HTML and the control structures. I edited it a bit, but it comes from a real-life template:

1
2
3
4
5
6
7
8
9
10
11
12
<?php if ($someCondition) { ?>
    <ul>
        <?php foreach ($someVar as $item) { ?>
             <li>
                <p>
                    <span class="name"><?php echo $item->name ?></span>
                    <?php echo $item->description ?>
                </p>  
             </li>
        <?php } ?>
    </ul>
<?php } ?>

Alternative syntax, indentation over HTML only:

1
2
3
4
5
6
7
8
9
10
11
12
<?php if ($someCondition) : ?>
<ul>
    <?php foreach ($someVar as $item) : ?>
    <li>
        <p>
            <span class="name"><?php echo $item->name ?></span>
            <?php echo $item->description ?>
        </p>  
    </li>
    <?php endforeach; ?>
</ul>
<?php endif; ?>

While my code-coloring plugin doesn’t do it justice, it is easier to read. For instance, if you look at the bottom, you will notice there was an if that started the <ul>, and right above the <?php endforeach; ?> there’s the </li>. When your templates grow this becomes ever more useful.

While I don’t want to tell you how to do your job, I would like to stress the point that templates have always been overlooked when it comes to coding standards. It doesn’t matter how you do it, but please take some time making your code easy to read for others.

An object assigning action helper

I’m sorry for the cryptic title, but I’ll explain it. One of the major challenges in software design nowadays is portability. It’s one of the cornerstones of object oriented programming. The basic idea being that if you define a class that describes some kind of thing, in any other applications that work with the same kind of thing, you can re-use the class.

Controllers are no different. I have mentioned this on my blog before, but it keeps popping up. If you plan on writing modules for an application, it pays to design them in such a way that they can be re-used in another project. Of course, some projects have specialized business logic that you will never need again. But if you have a look at totally different websites, some elements keep reoccurring. Things like contact forms, news sections, sitemaps, etc.

Eric Coleman, who hangs out a lot on #zftalk and I were having a chat about being lazy. It started when he said that having to type $this->_helper-> can be a bit cumbersome. Good programmers are lazy of course. I created a small action helper to assign all available helpers to the controller.

While doing so I found that Zend_Controller_Action_HelperBroker lacks a method to return all registered helpers. Apart from that writing it took me 5 minutes. Eric suggested to add a manual assign method to it as well, which was really a great idea. He did do a bad job on trying to implement it himself though, but I forgive him ;)

The benefit of having a manual assign method is that you can assign things you need in your controllers from outside controller context. You no longer need a subclassed controller, an init() method, or the Zend_Registry. For things like a database connection this can be handy, you can just use $this->_db from controller context, after altering your bootstrap, adding just three lines:

1
2
3
4
5
6
7
8
$assign = new Naneau_Action_Helper_Assign();
//assign action helper
Zend_Controller_Action_HelperBroker::addHelper($assign);
//add the helper to the helper broker

//create $db
$assign->assign('db', $db);
//make the db available to controllers as $this->_db

Too bad it relies on a patched Zend_Controller_Action_HelperBroker, but otherwise I’d release it. If you are interested in it’s inner workings, I suggest you check out this paste on pastebin.ca. You can expect a follow up on this.

Update

The Zend_Controller_Action_HelperBroker has been fixed in newer versions of the framework. So this helper now works out of the box :)

Two step view process

Most of you will be familiar with the problem that of every HTML page you generate, only a certain part changes from page to page. For instance, on this very website (which has been created using wordpress) only the posts differ from page to page. The head section is the same on every page, as is the sidebar.

In the comments for my posts on smarty as well as in #zftalk there is a recurring question about how to achieve this. There are basically two paths you can follow:

The first is to create views that include the different sections that stay the same using some kind of require. In smarty this would be done by the {include} tag. In Zend_View PHP syntax, it would be done with:

1
<?php $this->render('someTemplate.phtml'); ?>

This has the advantage of great control over what gets rendered where. It has a big disadvantage because there will be repetition. If you wanted to change the order in which things get included, you would have to change all your views. In general, repetition is bad.

The second approach is to do a “reverse include”. When writing controllers for your different pages, it makes sense to just render the bit that changes. You can then put the result into some kind of global template. This approach is called a “two step view“. If you just have a single repeating part, it’s incredibly easy to write a front controller plugin that gets the body out of the response object, render a global view, and put the result of that into the response.

There are a few schools of thought on this subject. While I believe in keeping things simple, sometimes a more complex approach is required. Sometimes not just a single part of the page changes, but multiple parts. Some applications have multiple global views, etcetera. Things will get out of hand quickly. Zend_Layout will address that, although I’ve been lead to believe that it will probably not make 1.0.

Update

It appears we will get a final way to do two-step-views/layouts in 1.1. Until then, I will redirect you to Spotsec’s site for a tutorial on [Xend/Zend]_view.

Searching for a blog name

I’m writing a small weblog application, based on the Zend Framework. I’m trying to make it so that it’s usable both as a set of modules, and as a standalone application. While it probably won’t be a wordpress killer, I do want to make it powerful enough to run my own site.

It’s interface is going to be very web 2.0. My thoughts are that if it needs php5 to run, I might as well make it state of the art in other aspects as well. It’s a nice way of putting some of the experiments run on naneau.nl together and creating something useful.

The only thing that’s really bugging me right now is a catchy name. I seem to be getting quite a few visitors nowadays. Maybe one of you has one? It has to be cute, yet descriptive. Preferably free of profanities and other offensive stuff ;)

A simple JSON action helper

JSON is my language of choice for communication between JavaScript and server side scripts. It’s lightweight, and it can be interpreted natively in JavaScript. That means that it’s usually the fastest way of getting information from your server to the browser of your users.

The Zend Framework has an excellent utility for encoding things, called Zend_Json. While it’s usage is ridiculously easy, there are some things you should take into consideration. JSON should be served with text/javascript headers, but JavaScript libraries like prototype also recognize the X-JSON header. Prototype will automatically parse the JSON it finds after that header.

In line with DRY and Zend Framework guidelines, I have created a small action helper that will send a JSON encoded response. You can pass it a single parameter with the thing you want encoded, and an optional second parameter if you want the response to be in a X-JSON header. Usage is easy:

1
2
3
4
//in controller context
$var = array('test' => true);
$this->_helper->json($var);
//send response

It is smart enough to call setNoRender() on viewRenderer if you have it enabled, so you don’t have to worry about that either. The only thing you have to do to set it up is add ‘Naneau/Controller/Action/Helper’, to your action helper broker paths:

1
Zend_Controller_Action_HelperBroker::addPath('Naneau/Controller/Action/Helper/', 'Naneau_Controller_Action_Helper');

Download Naneau_Controller_Action_Helper_Json 0.1

P.S.
Thanks to SpotSec who was able to find no less than 3 problems with my code ;)