One Time Actions with ZF View Helpers

It’s been a while since I have last written about Zend Framework, I guess and it’s won’t really be a long post. It’s more a personal reminder for myself on how I can run some commands in a view helper only once.

I don’t know if you use view helpers or not but I think it’s really a good way to abstract some logic from the view and move some functionality to classes instead of views.

Let’s get to the core of the problem. I have created a View Helper which highlights a code block. It uses a SyntaxHighlighter, a Javascript library for highlighting syntaxes. So the problem was I was adding the same style sheets and scripts again and again on the helper method. While ZF is smart on adding files — it does not add the same file twice, it’s not valid for adding script blocks. For each time I called the helper, I had a document.ready block, which I didn’t wanted. So I started to look out how the helpers were created and used.

You might knew like me that helpers are only created once and once they are created each time you call the helper you get the same instance. So there should have been a creation way of this Helpers. What I found finally was pretty simple: Constructor only gets called once! Surprise, ha? Yet this didn’t solved any of my problems, because once the helper was created it was not aware of the View it was called so I was not able to add style sheets etc.

Apart from constructor, if you create the setView method, it’s only called once right after the constructor. I hope that saves you some time.