Simple image view helper for Zend Framework

Last modified date

Comments: 2

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]<?php

class Zend_View_Helper_Img extends Zend_View_Helper_Abstract
{
protected $_baseurl = null;
protected $_exists = array();

/**
* Constructor
*/
public function __construct()
{
$url = Zend_Controller_Front::getInstance()->getRequest()->getBaseUrl();
$root = ‘/’ . trim($url, ‘/’);
if (‘/’ == $root) {
$root = ”;
}
$this->_baseurl = $root . ‘/’;
}

/**
* Output the <img /> tag
*
* @param string $path
* @param array $params
* @return string
*/
public function img($path, $params = array())
{
$plist = array();
$paramstr = null;
$imagepath = $this->_baseurl . ltrim($path, ‘/’);
if (!isset($this->_exists[$path])) {
$this->_exists[$path] = file_exists(realpath($_SERVER[‘DOCUMENT_ROOT’] . ‘/’ . $imagepath));
}
if (!isset($params[‘alt’])) {
$params[‘alt’] = ”;
}
foreach ($params as $param => $value) {
$plist[] = $param . ‘="’ . $this->view->escape($value) . ‘"’;
}
$paramstr = ‘ ‘ . join(‘ ‘, $plist);
return ‘<img src="’ .
(($this->_exists[$path])
? $this->_baseurl . ltrim($path, ‘/’)
: ‘data:image/gif;base64,R0lGODlhFAAUAIAAAAAAAP///yH5BAAAAAAALAAAAAAUABQAAAI5jI+pywv4DJiMyovTi1srHnTQd1BRSaKh6rHT2cTyHJqnVcPcDWZgJ0oBV7sb5jc6KldHUytHi0oLADs=’) .
‘"’ . $paramstr . ‘ />’;
}
}[/php]

Usage is really easy:

[php]<?php echo $this->img(‘/images/logo.png’, array(‘id’ => ‘logo’, ‘title’ => ‘Cool Company’)); ?>[/php]

Share

2 Responses

  1. 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.