views:

39

answers:

2

i am reading zend framework docs on zend view partials

If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the 'objectKey' property of the appropriate helper:

// Tell partial to pass objects as 'model' variable
$view->partial()->setObjectKey('model');

but what does this do. when do i use it and how.

A: 

Key as in array(key => value)?

Iznogood
+1  A: 

I'm not 100% positive on this, but from what I can tell by looking at the source and documentation is that standard behavior for rendering a partial is that values are passed into it in the form of an associative array. This allows the values to be bound to variables using array keys.

echo $this->partial('partial.phtml', array ('person' => 'joe');

// in my partial..
<h1><?php echo $this->person; ?></h1>  //<h1>Joe</h1>

If you pass an object as the third parameter, (ie, partial('partial.phtml', $myobject);), Zend_View_Partial will automatically serialize that object in an associative array, either by a custom implementation of toArray() or it will just grab the public properties via get_object_vars().

However, if you want to pass the whole object, as an object, you need to set the array key that gets transformed into a variable for the partial to reference.

$this->partial()->setObjectKey('myobject');
echo $this->partial('partial.phtml', $myobject);

What benefits this approach has over partial('partial.phtml', array( 'myobject' => $myobject), I'm not sure. Or I could be interpreting the documentation wrong.

Bryan M.
+1 yep, that's about it. To understand it easily, open up `Zend/View/Helper/Partial.php` and go to line ~91, there's the whole logic behind this.
robertbasic
i tried declaring a class with `__toArray()` then i tried using it with and without `setObjectKey()` both does not work (no output). [http://pastebin.com/hNR5KxfA](http://pastebin.com/hNR5KxfA) what do i pass into `setObjectKey()` btw? i used "article". when i used public properties with `stdClass()` it works [http://pastebin.com/TxMLpdrm](http://pastebin.com/TxMLpdrm)
jiewmeng
@Bryan, @jiewming: Just a small correction. If you invoke the partial with `$out = $view->partial('partial.phtml', array ('person' => 'joe');`, then I believe your usage within the view script should be `<?= $this->person ?>`, not `<?= $person ?>`. Similarly, for the invocation `$out = $view->partial('partial.phtml', $myobject);`, then your usage within the view script would be `<?= $this->myobject->someMethod() ?>`. I also see no difference between using `setObjectKey('myobject')` and `array('myobject' => $myobject)`.
David Weinraub
@DavidW That's right. I corrected the post.
Bryan M.