March 2010
S M T W T F S
28 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 1 2 3

Striped tables with Zend_View_Helper

I am currently working quite a lot with the Zend PHP Framework. I have grown to really like ZF (Zend Framework). While it does have a rather steep learning curve it is architected very neatly and offers lots of functionality for free.

I was recently constructing dynamic tables and wanted to give every other row a different class. Rather than clutter my view with logic to do this, I decided to create a custom view helper. I decided to make the view helper generic so it can be used to switch between two pieces of content each time it is called. This would mean I could use it for other things where alternating content is also needed.

The custom view helper code (RC_View_Helper_OddEvenSwitcher.php)

Below is the code for the custom view helper along with an example usage.

    1 <?php
    2 
    3 /**
    4  * Provides a way for a view to easily output alternate content each
    5  * timethe oddEvenSwitcher is called. It is particularly helpful 
    6  * in creating tables and generating odd/even classes for each row.
    7  *
    8  * @version 1.0
    9  * @author Rikki Carroll
   10  */
   11 class RC_View_Helper_OddEvenSwitcher extends Zend_View_Helper_Abstract
   12 {
   13     /**
   14      * How many times the view helper has been called.
   15      * @var int 
   16      */
   17     public static $callCount = 0;
   18     
   19     /**
   20      * Each time this method is called it keeps an internal count of 
   21      * how many times it has been called and if that count is even, 
   22      * it will return the even content, otherwise the odd content will 
   23      * be returned.
   24      * @param mixed $evenContent The value to return if even
   25      * @param mixed $oddContent The value to return if odd
   26      * @return mixed Either the even content passed in or odd content.
   27      */
   28     public function oddEvenSwitcher($evenContent, $oddContent)
   29     {
   30         self::$callCount++;
   31 
   32         // if the call count is even return the even content
   33         if ((self::$callCount%2) == 0) {
   34             return $evenContent;
   35         }
   36 
   37         // otherwise return the odd content
   38         return $oddContent;
   39     }
   40 
   41 }

To use this view helper to alternate a class on table rows you would place the following in your view files as follows:

    1 <tr class="<?php echo $this->oddEvenSwitcher('odd', 'even'); ?>">
    2     <!-- table cells here -->
    3 </tr>

The nice thing about this approach is that you do not need to keep a count in the view of how many rows you have output in your view. You simply call the view helper and it automatically keeps track of everything and returns the appropriate content - easy!

How to build custom view helpers

Building a custom view helper is very easy in the Zend Framework. The basic method is to:

  1. Create a file which the Zend Loader can see. Here I have used the same naming conventions as the Zend Framework so that I can automatically load any extensions to the Zend Framework without modifying Zend_Loader. In this case I created a file called OddEvenSwitcher.php in the “/RC/View/Helper/” directory.
  2. The class name should be the name of the directories from the include path all the way to the file you are writing the class in. So RC/View/Helper/OddEvenSwitcher.php becomes RC_View_Helper_OddEvenSwitcher.php. You basically just replace forward slash with underscore.
  3. The class you define must extend Zend_View_Helper_Abstract.
  4. The final thing to do is declare a method with the same name as your class but instead of the first letter being upper-case, it needs to be lowercase. You can also define whatever your parameters you want
  5. Essentially the name of this method is what you will use in the view. The class loading and instantiation is done automatically for you.

I am hooked on view helpers and have since gone on to create a mini-library of them for the project I am working on. They come with the nice mentality that you just write once, forget how you did it and just use them - cuts down on the code repetition and thinking you have to do, which is always good. If you have any thoughts, comments or suggestions please let me know by commenting below.

 

Comments

Wesley Walser

18 Feb 2009 at 02:32

“but instead of the first letter being upper-case, it needs to be lowercase”

Interesting fact, (and this definitely goes on my list akin to your earlier post about annoying things in PHP) php methods are case insensitive. I once spent well over two hours trying to find where a function was being declaired only to realize that the person who wrote the code had failed to camel case the method name. It is good practice in most languages to lower camel case method names though.

Now a question is every view in php a class in the zend framework? I assume that $this refers to the instance of the view. I ask this because I am wondering if you can have multiple ‘striped tables’ on a page where the top row in both tables is even despite the fact that both tables have an even number of rows.

Wesley Walser

18 Feb 2009 at 05:46

I should really proof read before hitting that submit button.

Is every view in the zend framework a class? I assume that $this refers to the instance of the view. I ask this because I am wondering if you can have multiple ‘striped tables’ on a page where the top row in both tables is even despite the fact that both tables have an even number of rows.

If the view is in fact a class then the static variable doesn’t really seem necessary but is probably ever so slightly faster.

Rikki Carroll

18 Feb 2009 at 11:48

$this does indeed refer to a Zend_View object. As far as i understand, there is typically only 1 Zend_View object in an application and it gets re-used for all the views. This doesnt mean you can’t have multiple it just reuses the same view object to save resources.

A view helper is a piece of functionality that you can “plug-onto” Zend_View. The way this works is that the Zend_View defines __call which intercepts method calls to undefined methods. Zend_View then uses some other classes to find the view helper and call the method on your custom class.

The class above would not make both of the top rows even becuase it relies on how many times you have called it. In order to achieve this you would need to modify the class.

The easiest way I can initially envisage is to accept a third, optional parameter, which is a boolean flag to reset the internal counter. A method signature like the following would be used.

public function oddEvenSwitcher($evenContent, $oddContent, $reset = false);

You would then call $this->oddEvenSwitcher(‘even’, ‘odd’, true); before iterating through the table rows.

Thinking about it a little more a second way would be to pass a name for a switcher and then return the switcher object as follows:
public function oddEvenSwitcher($name, $even, $odd);
You would then keep an internal assocative array of the switcher objects where the key is the name and the value is the object itself. Upon the view helper being called you check for the object in the array, if exists return it, otherwise create, insert and return it. The object would then declare a toString method so when the object is “echoed” it outputs the relevant content. The usage of this would be as follows:
$this->oddEvenSwitcher(‘myswitcher’, ‘even’, ‘odd’)

This would require changing the class a little bit. If you, or anyone would like to see the concrete code for this let me know.

Wesley Walser

24 Feb 2009 at 01:48

Thanks for the the follow up.