3

In Zend Framework we provide properties to layouts which are then consumed in the view. An example of this would be:

$this->layout = new Zend_Layout();
$this->layout->username = 'John';
$this->layout->email = 'john@foofoobunnies.edu';

Which I would later echo in my view.phtml:

<?= $this->username; ?>
<?= $this->email; ?>

However I find myself in Magento writing block methods that return entire objects to be consumed by the view - for instance:

Block/User.php

public function getUser(){
    return Mage::getModel('mymodule/user')->load($this->getUserId());
}

And in my user.phtml:

$user = $this->getUser();
echo $user->getUsername();
echo $this->getEmail();

Is there any way to cut out this step of having to write block methods to return relevant data? I've been using this method for 2-3 years so I'm no stranger to it, but it just seems like the Zend Two-Step/Composite view layout paradigm is much faster to hack on.

Edit

It just occurred to me that it may be possible to utilize block properties in the same manner that I utilize the block methods, e.g. $this->username where $this may be an object of type Mymodule_User_Block_User; though I don't know if this is an understood or accepted practice in Magento, as I haven't seen this too often.

1

There's always assign() and the aforementioned getters and setters via Varien_Object::_call()

  • I've never used assign, and this exactly what I was looking for. Fantastic, and thanks! – philwinkle Feb 24 '13 at 15:26
3

Your edit to your question pretty much sums it up.

You use $this when the block is an instance of what you are trying to access, within reason of course. A Block isn't going to be the equivalent of the respective Model you need.

But in terms of passing data to and through blocks, you can use XML or PHP to achieve it.

In PHP

$this->getLayout()->getBlock('block_name')->setData('user', Mage::getModel('mymodule/user')->load($this->getUserId())); 

Or in XML

<block type="mymodule/user" name="block_name">
  <action method="setUserId"><user_id>string_goes_here</user_id></action>
</block>

You could make your own action method to set the user object itself (obviously, I've crudely hardcoded a string, but the principal stands).

1

The toHtml() method in Mage_Core_Block_Template includes more or less the phtml file, therefore you are in the context of the Block. You can do everything the block or the Magento environment offers you.

Using $this->username is not best practice. I think because with the get method, you are absolutely free to change something later, without changing the core logic with the data array, extended from Varien_Object. Add a check, override the standard __get() with getUsername() and return something else than in the data array, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.