Magento – Blocks

Blocks and layouts are pretty well integrated and to divide the two can seem a little confusing.  However they are distinct, so let us consider how Magento uses blocks and what they can do for your project.

Things to remember:

Blocks are tied to one to a single Template file. Inside a phtml file, PHP’s $this keyword will contain a reference to the Template’s Block object. (rephrase)

A Block can be defined as the logic that relates to the functioning of a page.

Block types: page/html, page/html_head, page/html_notices, page/html_header, page/html_wrapper, page/html_breadcrumbs, page/html_footer, page/template_links, page/switch, core/messages, core/text_list & core/profiler.

Looking at the above list it is logical to ask, what is the difference between the various block types and how does this list actually help in extending or modifying the Magento functionality.  Valid point and something that is worth explaining in greater depth.

It is necessary to consider the role of the layout.xml file and more information can be seen on the layout page.

Consider the Block structure diagram that is found at: http://www.magentocommerce.com/knowledge-base/entry/standard-block-layout

From this image it is possible to see the relationship of various blocks and how nesting of blocks occurs.

Consider the top level root layout, this can be seen to be defined by the block page/html, and this is composed of other layout and block elements.  Which are called with the use of getChildHtml.  However all of this still seems a little vague.  So here is an example to explain things a little more procedurally.

Create the following new directories and files:

/app/code/etc/modules/Howto_Blockexample.xml


<Howto_Blockexample>
true
local

/app/code/local/howto/blockexample/

/app/code/local/howto/blockexample/Blocks
/app/code/local/howto/blockexample/Blocks/Example.php

/app/code/local/howto/blockexample/etc
/app/code/local/howto/blockexample/etc/config.xml


<Howto_Blockexample>
0.1.0

Howto_Blockexample_Block

Nested Blocks

 

Resources:

http://www.magentocommerce.com/knowledge-base/entry/standard-block-layout

http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-4-magento-layouts-blocks-and-templates