Sunday, April 14, 2013

Magento : Custom router in Magento

Suppose, we need to create a custom url like 'abc' for test/test/index

1. Define an event in config.xml
<events>
            <controller_front_init_routers>
                <observers>
                    <test>
                        <class>Bd_Test_Controller_Router</class>
                        <method>initControllerRouters</method>
                    </test>
                </observers>
            </controller_front_init_routers>
 </events>

2. Then define router class in Controller folder
<?php

class Bd_Test_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract
{
    /**
     * Initialize Controller Router
     *
     * @param Varien_Event_Observer $observer
     */
    public function initControllerRouters($observer)
    {
        /* @var $front Mage_Core_Controller_Varien_Front */
        $front = $observer->getEvent()->getFront();

        $front->addRouter('test', $this);
    }

    /**
     * Validate and Match Cms Page and modify request
     *
     * @param Zend_Controller_Request_Http $request
     * @return bool
     */
    public function match(Zend_Controller_Request_Http $request)
    {
        if (!Mage::isInstalled()) {
            Mage::app()->getFrontController()->getResponse()
                ->setRedirect(Mage::getUrl('install'))
                ->sendResponse();
            exit;
        }

        $identifier = trim($request->getPathInfo(), '/');

        $condition = new Varien_Object(array(
            'identifier' => $identifier,
            'continue'   => true
        ));
       
       
      
        if ($condition->getRedirectUrl()) {
            Mage::app()->getFrontController()->getResponse()
                ->setRedirect($condition->getRedirectUrl())
                ->sendResponse();
            $request->setDispatched(true);
            return true;
        }

        if (!$condition->getContinue()) {
            return false;
        }

      
        if ($identifier!='abc') {
            return false;
        }

        $request->setModuleName('test')
            ->setControllerName('test')
            ->setActionName('index');
          
        $request->setAlias(
            Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
            $identifier
        );       

        return true;
    }
}


No comments:

Post a Comment