开发者

How to turn a zend helper to a singleton?

开发者 https://www.devze.com 2023-01-30 11:32 出处:网络
I need to use a view helper to make counts in a bunch of different partials. 开发者_Python百科In the partials I can\'t access view variables, but I can access helpers, so I created this simple class.

I need to use a view helper to make counts in a bunch of different partials. 开发者_Python百科In the partials I can't access view variables, but I can access helpers, so I created this simple class.

class Zend_View_Helper_Counter extends Zend_View_Helper_Abstract{
    protected $count = 0;
    public function counter(){
        return $this;
    }
    public function add($i = 1){
        $this->count = $this->count + (int) $i;
        return $this;   
    }
    public function get(){
        return $this->count;    
    }
    public function set($count){
        $this->count  = (int) $count;
        return $this;   
    }
}

However this <?php echo $this->counter()->add()->get()?> Always returns 1. I guess this is because it's always a different instance of the class. How would I need to change the counter() function so that it can count through all the views and partials?


  1. Use statics:

    static protected $count = 0;
    public function add($i = 1){
      self::$count = self::$count + (int) $i;
      return $this;   
    }
    
  2. Write a separate counter singleton and then do:

     public function get(){
       return Counter::getInstance();
     }
     public function add($i = 1){
        Counter::getInstance()->add($i);
        return $this;
     }
    

If you want, you may also extend it by using named counters and then $count would be an array.

0

精彩评论

暂无评论...
验证码 换一张
取 消