PHP Magento Tips

Magento Basic Module initialization, Layout and Request Flow in Magento

Rate this posting:
{[['']]}

This Example illustrates the Basic declaration of Blocks, Models, Resource Models and Helpers. In Magento each Module can declare its own database connection configuration. It also allows to use of a different database or different storage. Sometimes it helps to view old orders (from old database) without data migration.

Step 1:

In app/etc/modules/Day_Two.xml add below code:

<?xml version="1.0" encoding="UTF-8"?>
<!-- /app/etc/modules/Day_Two.xml -->
<config>
  <modules>
    <Day_Two>
      <active>true</active>
      <codePool>local</codePool>
      <depends>
          <Mage_Log />
      </depends>
    </Day_Two>
  </modules>
</config> 

Here we add dependency with Mage_log. So make sure it is active in Mage_All.xml and also check in Admin under System >> Configuration >> Advanced and Expand Disable Modules Output tab. Check Mage_Log is Enabled.
Step 2: 

In app/code/local/Day/Two/etc/config.xml add Below code:

<?xml version="1.0" encoding="UTF-8"?>
<!-- app/code/local/Day/Two/etc/config.xml -->
<config>
    <modules>
        <Day_Two>
            <version>0.1.0</version>
        </Day_Two>
    </modules>
 <global>
         <blocks>
             <day_two><!-- That's a class group -->
                <class>Day_Two_Block</class><!-- That's a path to these object types -->
            </day_two>
         </blocks>
         <helpers>
             <day_two>
                <class>Day_Two_Helper</class>
            </day_two>
         </helpers>
         <models>
            <day_two>
                <class>Day_Two_Model</class>
            </day_two>
         </models>
  </global>
  <frontend>
    <routers>
        <day_two><!--unique node-->
            <use>standard</use>
            <args>
                <module>Day_Two</module>
                <frontName>heyo</frontName>
            </args>
        </day_two>
    </routers>
    
    <layout>
        <updates>
            <bens_layout>
                <file>day_two/custom.xml</file>
            </bens_layout>
        </updates>
    </layout>
    </frontend>
    
</config> 

Here under <frontend> <routers> <args> <module> node you have to pass your Module information. And your Module information exactly math with your file system path to your controllers directory.

Step 3:

In app/code/local/Day/Two/controllers/IndexController.php add below code:

<?php

// app/code/local/Day/Two/controllers/IndexController.php
class Day_Two_IndexController extends Mage_Core_Controller_Front_Action {
    
    Public function indexAction() {
        echo 'we\'re cookin now!';
    }
    
    Public function modelAction() {
        echo get_class(Mage::getModel('day_two/whatever'));
    }
    
    Public function layoutAction() {
        $xml = $this->loadLayout()->getLayout()->getUpdate()->asString();
        $this->getResponse()->setHeader('Content-Type','text/plain')->setBody($xml);
        //Mage::log($xml,Zend_Log::INFO, 'layout.log', true);
        $model= Mage::getModel('day_two/whatever');
        Mage::log($model->debug(),Zend_Log::INFO, 'model.log',true);
    }
    Public function defaultAction() {
        $this->loadLayout()->renderLayout();
    }
}
 
To work layoutAction properly make sure Log is Enabled under System >> Configuration >> Developer and check Log Settings Tab. Here in Mage::log We pass fourth Parameter 'true' which will forcefully Enable Magento Log.


Step 4:

In  app/code/local/Day/Two/Model/Whatever.php add below code:

<?php

// app/code/local/Day/Two/Model/Whatever.php
class Day_Two_Model_Whatever extends Mage_Core_Model_Abstract {
    
    
} 

Step 5:

In app/design/frontend/vijay/default/layout/day_two/custom.xml add below code:  

<?xml version="1.0" encoding="UTF-8"?>
<layout>
 
 <catalog_product_view><!--catalog_product_view -->
  <reference name="content">
   <block type="core/text" name="oops">
    <action method="setText">
     <arg><![CDATA[<h1>This is Some text!</h1>]]></arg>
    </action>
   </block>
  </reference>
  
  <reference name="product.info">
   <action method="setThisDoesntExist">
     <abcdefg>
      <key1>This is a String!</key1>
      <key2>Another String!</key2>
     </abcdefg>
   </action>
  </reference>
  
 </catalog_product_view><!-- catalog_product_view -->
 
 <cool_handle>
  <block type='core/template' 
    name='some.name' 
    output='toHtml'
         template='some/template.phtml' >
         
       <block type='core/text' name='some.otherBlock'> <!-- child block -->
         <action method='setText'>
           <argu>Some random text!</argu>
         </action>
     </block>
     
       </block>
       
 </cool_handle>
 
 <day_two_render_final>
  <update handle="cool_handle" />
 </day_two_render_final>
 
</layout>

Step 6:
 
In app/design/frontend/yourtheme/default/template/some/template.phtml add below code:

<h1>This is Some Template!</h1>
<?php echo $this->getChildHtml('some.otherBlock'); ?>


In your  app/design/frontend/yourtheme/default/template/catalog/product/view.phtml file search for

<div class="product-name">
                    <span class="h1"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></span>

</div>


and replace with below code:

<div class="product-name">

                    <span class="h1"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->getThisDoesntExist('key1') ?></span>

</div>


In your browser, navigate below URL:
Site.com/heyo
Site.com/heyo/index/model
Site.com/heyo/index/layout
Site.com/heyo/index/default

Also check in var/log folder. You will find layout.log and model.log file under it.

Now, just modify your config.xml file. Change name of <frontName> node. 

<frontend>
    <routers>
        <day_two><!--unique node-->
            <use>standard</use>
            <args>
                <module>Day_Two</module>
                <frontName>custom</frontName>
            </args>
        </day_two>
    </routers>
</frontend>

In app/code/local/Day/Two/controllers/RenderController.php add below code:

<?php
//app/code/local/Day/Two/controllers/RenderController.php
class Day_Two_RenderController extends Mage_Core_Controller_Front_Action {
 
 public function blockAction() {
  $this->getResponse()->setBody('Hello Magento');
 }
 public function overrideAction() {
  $blockhtml = $this->getLayout()->createBlock('day_two/sample')->tohtml();
  $this->getResponse()->setBody($blockhtml);
 }
 public function templateAction() {
  $blockhtml = $this->getLayout()->createBlock('core/template')->setTemplate('day_two/random.phtml')->toHtml();
  $this->getResponse()->setBody($blockhtml);
 }
 public function registryAction() {
  Mage::register('some_var', 'Some value.');
  $blockhtml = $this->getLayout()->createBlock('day_two/registry')->setTemplate('day_two/registry.phtml')->toHtml();
  $this->getResponse()->setBody($blockhtml);
 }
 public function listBlockAction() {
 
  $tlb = $this->getLayout()->createBlock('core/text_list');
  $blockA = $this->getLayout()->createBlock('core/text')->setText('<h1>Block A</h1>');
  $blockB = $this->getLayout()->createBlock('core/text')->setText('<h1>Block B</h1>');
  $tlb->insert($blockA)->insert($blockB);
  //$this->getResponse()->setBody($tlb->toHtml());
  $this->loadLayout();
  $this->getLayout()->getBlock('content')->insert($tlb);
  $this->renderLayout();
 }
 public function layoutAction() {
  
  $blockhtml = $this->loadLayout()->renderlayout();
 }
 public function handleAction()
 {
  $this->loadLayout('cool_handle')->renderLayout();
 }
 public function finalAction()
 {
  $this->loadLayout()->renderLayout();
 }
}

In app/code/local/Day/Two/Block/Sample.php add below code:


<?php

// app/code/local/Day/Two/Block/Sample.php
class Day_Two_Block_Sample extends Mage_Core_Block_Template {
    
    protected function _tohtml() {
        //parent::_tohtml();
        return 'Hello Magento From'.__FILE__;
        return 'Hello Magento From'.__CLASS__;
        return 'Hello Magento From'.__METHOD__;
    }
} 

In app/design/frontend/yourtheme/default/template/day_two/random.phtml add below code:
 
<h1>Here's a template and class -
<?php echo get_class($this); ?></h1>

In app/code/local/Day/Two/Block/Registry.php add below code:

<?php
// app/code/local/Day/Two/Block/Registry.php
class Day_Two_Block_Registry extends Mage_Core_Block_Template {
    
    protected function _toHtml() {
        $var = Mage::registry('some_var');
        return ($var) ? $var : 'You did not set the var!';
    }
}

In your Browser Navigate with below URLS:
Site.com/custom/render/block
Site.com/custom/render/override

Site.com/custom/render/template
Site.com/custom/render/registry
Site.com/custom/render/layout
Site.com/custom/render/listblock
Site.com/custom/render/handle
Site.com/custom/render/final

Check any Product page and change <?php echo $this->getThisDoesntExist('key2') ?> in app/design/frontend/yourtheme/default/template/catalog/product/view.phtml to see different text.
 
In  app/code/local/Day/Two/Block/Sample.php comment and uncomment line no. 8,9,10 Properly, to see different results.


Now For better Understanding of Mage::getResourceModel and Mage::getModel Follow Below Step:

In  app/code/local/Day/Two/controllers/ModelsController.php add below code:

<?php
// app/code/local/Day/Two/controllers/ModelsController.php

class Day_Two_ModelsController extends Mage_Core_Controller_Front_Action {
    
    public function storesAction() {
        $stores = Mage::getResourceModel('core/store_collection');
        //$stores = Mage::getModel('core/store')->getCollection();
        echo '<h2 style="color: red;">' . get_class($stores) . '</h2>';
        foreach ($stores as $store) {
            //echo '<h2 style="color: red;">' . get_class($store) . 
                // ' - '.$store->getRootCategoryId().'</h2>';
            //echo '<h2> &nbsp &nbsp: '.$store->getName().' --   ' .$store->getCode(). '</h2>';
            $category = Mage::getModel('catalog/category')->load($store->getRootCategoryId());
            echo '<h2>'.$category->getName().'</h2>';
        }
    }
    
    public function categoriesAction() {    
        /*$categories = Mage::getResourceModel('catalog/category_collection')
                                            ->addFieldToFilter('level',1)
                                            ->addAttributeToSelect('name');*/
        $categories = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('level',1);
        
        /*foreach ($categories as $category) {
            echo '<h2>' . $category->getId() . '   ' .$category->getName() . '</h2>';    
        }*/
        
        foreach ($categories as $category) {
            $children = $category->getChildren();
            $childrenIds = explode(',',$children);
            foreach ($childrenIds as $child) {
                $_category = Mage::getModel('catalog/category')->load($child);
                //ZEND_DEBUG::dump($_category->debug());
                if($_category->getIsActive())
                {
                    $caturl     = $_category->getURL();
                    $catname     = $_category->getName();
                    if($_category->getImageUrl())
                    {
                        $catimg     = $_category->getImageUrl();
                    }
                    echo '<h2><a href="'.$caturl.'" title="View the products for this category"><img src="'.$catimg.'" alt="" />'.$catname.'</a></h2>';
                }
            }
                
        }
    }
    
}

Also Check core_store and catalog_category_entity table once for better understanding.

Now in your browser, navigate with below urls:

Site.com/custom/models/stores
Site.com/custom/models/categories
Tag : Magento
0 Comments On "Magento Basic Module initialization, Layout and Request Flow in Magento"

Back To Top