Simple image view helper for Zend Framework

Here's a simply view helper for the Zend Framework that can be used to display image tags. It checks to see if the image file exists and if not then it'll use the data url scheme to output a very simple image that, ironically, says 'NO IMG' on it. :-) Please note, though, that I've only seen Firefox support this scheme, as wonderful as it is!

PHP:
  1. <?php
  2.  
  3. class Zend_View_Helper_Img
  4. {
  5.     public $view;
  6.     protected static $_baseurl = null;
  7.     protected static $_cache = null;
  8.    
  9.     /**
  10.      * Constructor
  11.      */
  12.     public function __construct()
  13.     {
  14.         if (null === self::$_baseurl) {
  15.             $url = Zend_Controller_Front::getInstance()->getRequest()->getBaseUrl();
  16.             $root = '/' . trim($url, '/');
  17.             if ('/' == $root) {
  18.                 $root = '';
  19.             }
  20.             self::$_baseurl = $root . '/';
  21.         }
  22.     }
  23.  
  24.     /**
  25.      * Output the <img> tag
  26.      *
  27.      * @param string $path
  28.      * @param array $params
  29.      * @return string
  30.      */
  31.     public function img($path, $params = array())
  32.     {
  33.         $plist = array();
  34.         $paramstr = null;
  35.         $imagepath = self::$_baseurl . ltrim($path, '/');
  36.         if (!isset(self::$_cache[$path])) {
  37.             self::$_cache[$path] = file_exists(realpath($_SERVER['DOCUMENT_ROOT'] . '/' . $imagepath));
  38.         }
  39.         if (!isset($params['alt'])) {
  40.             $params['alt'] = '';
  41.         }
  42.         foreach ($params as $param => $value) {
  43.             $plist[] = $param . '="' . $this->view->escape($value) . '"';
  44.         }
  45.         $paramstr = ' ' . join(' ', $plist);
  46.         return '<img src="' .
  47.                 ((self::$_cache[$path])
  48.                     ? self::$_baseurl . ltrim($path, '/')
  49.                     : 'data:image/gif;base64,R0lGODlhFAAUAIAAAAAAAP///yH5BAAAAAAALAAAAAAUABQAAAI5jI+pywv4DJiMyovTi1srHnTQd1BRSaKh6rHT2cTyHJqnVcPcDWZgJ0oBV7sb5jc6KldHUytHi0oLADs=') .
  50.                 '"' . $paramstr . ' />';
  51.     }
  52.  
  53.     /**
  54.      * Set the view object
  55.      *
  56.      * @param Zend_View_Interface $view
  57.      * @return void
  58.      */
  59.     public function setView(Zend_View_Interface $view)
  60.     {
  61.         $this->view = $view;
  62.     }
  63. }

Usage is really easy:

PHP:
  1. <?php echo $this->img('/images/logo.png', array('id' => 'logo', 'title' => 'Cool Company')); ?>

1 Response to “Simple image view helper for Zend Framework”


  1. 1 Andy

    Just update the code so that it uses the escaping method of the view (rather than htmlentities directly) and also to always have an alt parameter, even if it’s empty.

Leave a Reply

You must login to post a comment.