YASB – Yet Another Symfony Blog

January 10, 2007

Back to basics: templating with helpers

Filed under: General, PHP, Tips and tricks — Krof Drakula @ 4:31 pm

If you’re like me (eg. lazy), you’ll have probably tried to make your code as efficient as possible, when it comes to generating output code. And in some cases, you can’t get around declaring your own functions to do your bidding. That’s where helpers come in.

A helper is nothing more than a PHP file containing dependency and function declarations. You can use functions within if you declare your use for it by issuing a call to use_helper. A common helper, for example, is the Object helper, which enables you to link Propel objects to HTML form tags via use of object_*_tag functions.

Here’s an example. Say you’re listing a lot of unordered lists of Propel objects. You’ve taken the time to write __toString() functions for your Propel classes. The obvious is this – you could make a function generic enough to list your objects, like so:

  [?php foreach($objects as $object): ?]
    <li>[?php echo $object-&gt;__toString(); ?]</li>
  [?php endforeach; ?]

It hits you immediately – you could just make a single function that takes $objects and outputs the above code. But, copy/pasting the function to different templates presents a problem – what if you happen to declare the function twice? Fatal errors occur.

The solution is to put that function in a helper. We pick a name, MyList. We create a new file in /lib/helper/MyListHelper.php, which represents our helper (the naming convention dictates you need to add Helper to make autoloading work). Let’s name our function list_objects() and put the following content in MyListHelper.php:

function list_objects($source_objects, $text_if_null = "") { 
  if(is_array($source_objects) &amp;&amp; (count($source_objects) &gt; 0)) {
    $output = "<ul>";
    foreach($source_objects as $object) {
      $output .= "<li>" . $object-&gt;__toString() . "</li>";
    $output = "</ul>";
  } else {
    $output = $text_if_null;
  return $output;

I’ve taken the libery to add another argument – $text_if_null. This parameter contains output in case $source_objects happens to be null or an empty array.

Now, we take our template and change the previous code simply to (assuming we’ve populated the template variable $objects within our action):

[?php use_helper("MyList"); ?]

[?php echo list_objects($objects); ?]

Sorry for the mangled PHP code, but the blog software seems to chomp up everything even remotely smelling of code injection.

1 Comment

  1. [...] There’s an interesting aspect about using functions within partials, which I’ve written about before – the existence of functions and the dangers of redeclaring them. [...]

    Pingback by YASB - Yet Another Symfony Blog » Blog Archive » A PHP gotcha within Symfony — June 22, 2007 @ 10:45 am

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress