Saturday, October 2, 2010

What is the difference between partial and render in Zend PHP?

A view script can be rendered in Zend using partial and render method. Every view script rendered by the view object, will have the entire variable scope of the script preceeding it. This will lead to some unwanted issues, when you want to re-use the script multiple times, or if you want to manipulate the variables, which will lead to other issues for the later scripts.
For example, you have a shared view script which is used to display the Ads in your index page, based on the position variable. Suppose in your index page, you are calling the Ads script in the top as well as bottom of your page, by using the render method and you have your position variable initialized to some value through controller and sticked on to the view, the the same value will be in scope throughout the script for the Ads call for both top and bottom, unless it is changed everytime before the shared Ads call is rendered, which will create some awkward issues in displaying the Ads. To overcome this issue
Enters partial: The big difference between rendering the script using partial and render is that, partial will have its own variable scope, it doesn't see any variables associated to the view, it only see the variable passed to it directly. As an example take the following

$this->Ads('/shared/viewAd.phtml', array('position' => "top", 'groupId' => '1223'));

1 comment:

  1. Useful stuff! Thanks for explaining it so well.