Skip to content

Instantly share code, notes, and snippets.

@Kalyse
Created July 22, 2011 19:02
Show Gist options
  • Save Kalyse/1100142 to your computer and use it in GitHub Desktop.
Save Kalyse/1100142 to your computer and use it in GitHub Desktop.
ClassCounter
<?php
// The ViewHelper
class My_View_Helper_ClassCounter extends Zend_View_Helper_Abstract
{
protected $_registry;
public function __construct()
{
$this->_registry = My_View_Helper_ClassCounter_Registry::getRegistry();
}
public function classCounter($name)
{
$name = (string) $name;
return $this->_registry->getContainer($name);
}
}
// The Container
<?php
class My_View_Helper_ClassCounter_Container
{
protected $_namespace;
protected $_count = 0;
protected $_modelCount = 0;
private $_state = true;
public function resetCounter()
{
$this->_count = 0;
$this->_modelCount = 0;
return $this;
}
public function pauseCounter(){
$this->_state = false;
}
public function incrementCounter(){
$this->_count++;
}
public function setCounter($count = 0){
$this->_count = $count;
}
public function toString()
{
$string = "";
if($this->_count == 0) $string .= "first ";
if($this->_count == $this->_modelCount - 1) $string .= " last ";
if($this->_state) $this->incrementCounter();
$string .= ((boolean) (int)( $this->_count % 2)) ? " odd " : " even ";
return (string) trim($string);
}
/**
* Cast to string representation
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
public function setModel($model){
if(is_array($model)){
$this->_modelCount = count($model);
} elseif(is_numeric($model)){
$this->_modelCount = $model;
} else {
throw new Zend_Exception("Incorrect Parameter passed to setModel() in My_View_Helper_ClassCounter_Container");
}
return $this;
}
}
// The Registry
class My_View_Helper_ClassCounter_Registry
{
const REGISTRY_KEY = 'My_View_Helper_ClassCounter_Registry';
protected $_items = array();
protected $_containerClass = 'My_View_Helper_ClassCounter_Container';
public static function getRegistry()
{
if (Zend_Registry::isRegistered(self::REGISTRY_KEY)) {
$registry = Zend_Registry::get(self::REGISTRY_KEY);
} else {
$registry = new self();
Zend_Registry::set(self::REGISTRY_KEY, $registry);
}
return $registry;
}
public function getContainer($key)
{
$key = (string) $key;
if (isset($this->_items[$key])) {
return $this->_items[$key];
}
$container = $this->createContainer($key);
return $container;
}
public function createContainer($key, array $value = array())
{
$key = (string) $key;
$this->_items[$key] = new $this->_containerClass(array());
return $this->_items[$key];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment