Zend_View_Helper vs Zend View Partial Script

2020-07-10 12:12发布

问题:

This is my fork in the road.

I want to display some sort of button on my webpage and I want to do it in many places. This 'button' is really just gonna act like a link to some other page and all the button instances are gonna go to one page.

I want all the buttons to be the same except for maybe the size that they are.

Now, should I use a partial script with the html for the button and call the partial view helper to render or should I create a Zend_View_Helper that will return the html for the button when I call it?

I know that I could swing either way but which do you think is better?

Some things I see :

  1. The helper might be better because it wouldn't have to create a BIG object like a clone of a Zend_View to do the partial.

  2. The partial script would be easier for an html person to work with.

回答1:

Use $this->render() instead of $this->partial().

Only use partials when you need more control over the scope. Like you said, it has a lot of overhead since it has to create a new Zend_View instance. Using render doesn't.

To touch upon your actual question, I recommend using render (or partial) over a view helper because it's much simpler for designs to work with, and there is less overhead. View helpers are for custom functionality.

A good rule of thumb is: do you want to include content/html, or do you want to generate content / apply transformations. Helpers are for the latter.



回答2:

Based on your description I would suggest using partial for your task. The reason is that your button seems to be mainly html, without much php. You could pass the size to the partial and that would be it. However, if you would like to include more logic into generation of your button (e.g. database, auth or acl queries) I would suggest view helper.

p.s. The third option would be to use both partial and view helper, maybe not for this particular case, but in more general sense. You could have helper that does to php part and this helper call partial to return desired html.



回答3:

I tend to use a view helper any time I need very parameterized values. For example:

echo $this->button('Button Text', '/foo/bar/baz');

Looks much better than:

$this->buttonText = 'Button Text';
$this->buttonUrl = '/foo/bar/baz';
echo $this->render('button.phtml');

Also, there's no reason you can't render a view script from within your view helper.