In our first installment, we saw how we can quickly create a Magento template file with specific functionality. However, this clashes with the paradigm of separating design from business logic and can lead to the habit of implementing increasingly complex functionality in our presentation layer. Just imagine if we were to extend the set of features of our random block. Soon it would be full of PHP code.
To correct our approach and make the code future proof, we can create an extension to encapsulate the code properly, provide some more flexibility and, of course, the ability to distribute the code via Magento Connect or file download.
Our .phtml block will have it’s own Block class that will provide the utility methods to retrieve the random block. I will also add some code to automatically determine how many blocks with the given identifier prefix are enabled instead of passing the number of available blocks. Finally, if there is no title provided for our random block, my code will retrieve and use the title of the CMS block instead. These additional features will give our random testimonial block some more flexibility.
We will provide a Helper class as well. While it will be just an empty class, it is necessary to provide in case you want to add translatable language strings to the Block class or classes in the future. We have also provided the language
.csv file for the en_US locale.
On the front end, our extension will provide a layout file and one phtml template. The extension for download here is compatible with Magento 1.4 only. The template files are located in the
base template. If you are installing this in Magento < 1.4, you will need to move the files from
default. See Starting a New Design Package for more details about Magento templates.
I won’t go into detail explaining the extension code, feel free to examine it at your own leisure. The code is commented and should be self explanatory.
The version provided here will install itself under the local namespace. Simply unarchive the download in your Magento site root and browse to your site to install. The supplied layout file will add the random block to the product view page only but you can modify this as you see fit and add more blocks wherever you need them. The methods of adding the block that are described above will work here as well.
Again, do not install this directly on a Magento 1.3 or lower site. You must first move the template files into your custom or the default design package.
Originally published on magebase.com. Copyright © 2010 Magebase - All Rights Reserved.