Tag cloud view helper
Here’s a little view helper to display a tag cloud. All you have to do is supply an array of tags, with the tag name being the index and how many times it’s used as the value, and the url you’d like the tags to go to.
[php]< ?php
/**
* Display a tag cloud
*
* @category Amnuts
* @package Amnuts_View
* @subpackage Amnuts_View_Helper
* @copyright Copyright (c) 2008 Andrew Collington (http://www.amnuts.com/)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Amnuts_View_Helper_TagCloud
{
public $view;
/**
* Output the tag cloud.
*
* The $tags parameter is expected to be an array with the tag being the
* index and the number of times it's used as the value. For example:
*
* array(
* 'foo' => 3,
* ‘bar’ => 1,
* ‘dog’ => 5,
* ‘cat’ => 1
* )
*
* The url will have the tag text appended to it, so that if you supply
* ‘/filter/by/tag/’ as the url, then given the above array you will have:
*
* foo
* bar
*
* and so on.
*
* @param array $tags The tag array
* @param string $url The link for each tag (with the tag name appended)
* @param int|string $minFont The minimum font value
* @param int|string $maxFont The maximum font value
* @param string $unit The unit of size type (%, em, px, etc.)
* @return string
*/
public function tagCloud(array $tags, $url, $minFont = 100, $maxFont = 150, $unit = ‘%’)
{
$xhtml = ”;
$cloud = array();
if (!empty($tags)) {
$min = min(array_values($tags));
$max = max(array_values($tags));
$diff = $max – $min;
if (!$diff) {
++$diff;
}
foreach ($tags as $tag => $count) {
$size = $minFont + ($count – $min) * ($maxFont – $minFont) / $diff;
$cloud[] = ‘‘
. $this->view->escape($tag) . ‘‘;
}
$xhtml .= ‘
Tag cloud
‘ . join(‘, ‘, $cloud) . “
\n”;
}
return $xhtml;
}
/**
* Set the view object
*
* @param Zend_View_Interface $view
*/
public function setView(Zend_View_Interface $view)
{
$this->view = $view;
}
}
?>[/php]