Mini Tutorial:
Magento Layout Loading

The Magento Layout (located in app/design/frontend/your_interface/your_theme/layout/): these are basic XML files that define block structure for different pages as well as control META information and page encoding. For in-depth look into layouts, read Intro to Layouts

So, how does Magento load the layout? Let’s take a look. The most fundamental responsibility for any Magento action is to load and render the layout. A basic action could look something like this:

extends Mage_Core_Controller_Varien_Action

public function basicAction()
{
$this->loadLayout();
$this->renderLayout();
}

Of course Magento being what it is, things are not always this straightforward; for example the catalog/product/view action (in Mage_Catalog_ProductController) uses a view helper (Mage_Catalog_Helper_Product_View) which duplicates much of the functionality of Mage_Core_Controller_Varien_Action::loadLayout() but we won’t get into that right now.

Here is Mage_Core_Controller_Varien_Action::loadLayout() for reference:

public function loadLayout($handles=null, $generateBlocks=true, $generateXml=true)
{
// if handles were specified in arguments load them first
if (false!==$handles && ''!==$handles) {
$this->getLayout()->getUpdate()->addHandle($handles ? $handles : 'default');
}

// add default layout handles for this action
$this->addActionLayoutHandles();

$this->loadLayoutUpdates();

if (!$generateXml) {
return $this;
}
$this->generateLayoutXml();

if (!$generateBlocks) {
return $this;
}
$this->generateLayoutBlocks();
$this->_isLayoutLoaded = true;

return $this;
}

The actual layout is a singleton instance of Mage_Core_Model_Layout which is stored in the registry. The controller accesses the layout through $this->getLayout() and manipulates it throughout the loading process.

The layout creates itself by means of a protected variable $_update of type Mage_Core_Model_Layout_Update. This object keeps track of the configuration directives which will be needed to assemble the complete layout. The update object stores the directives in two protected arrays $_updates and $_handles until assembly time ($this->generateLayoutXml() above).

So where does the developer come into all this? We make use of this by creating layout XML files in the design//// folder which will be parsed by this apparatus in the creation of the full layout. The exact syntax for these layout XML files relates to how blocks are generated from the layout and will have to be the subject of another blog post.