How to override magento core code controller

What is Controllers and why we need to override Controllers?

In Magento, the controller is responsible for handling incoming requests, and it's a backbone of the Magento routing implementation. To handle probably every request in Magento, the controller defines different actions in the form of controller class methods. The controller action method includes related application logic which interacts with views and models to prepare the output of that particular page. Sometimes, you need to alter the flow of controller execution to inject custom code or change the core code.

  • Let's create custom module in local code pool.
  • First of all we need enable our module

PATH : app/etc/modules/Animex_Catalog.xml



  
    
      true
      local
    
  

Module configuration file with overriding magento tag before="Mage_catalog".

PATH : app/code/local/Animex/Catalog/etc/config.xml



  
    
      1.0
    
  
  
    
      
        
          
            Animex_Catalog
          
        
      
    
  

Custom controller class file with extends keywords and we are going to override viewAction of product to no route 404.

PATH : app/code/local/Animex/Catalog/controllers/ProductController.php

<?php

 /**
 * Product controller
 *
 * @category   Animex
 * @package    Animex_Catalog_ProductController override
 */

require_once 'Mage/Catalog/controllers/ProductController.php';
class Animex_Catalog_ProductController extends Mage_Catalog_ProductController
{
    /**
     * Product view action
     */

    public function viewAction()
    {
        // Get initial data from request
        $categoryId = (int) $this->getRequest()->getParam('category', false);
        $productId  = (int) $this->getRequest()->getParam('id');
        $specifyOptions = $this->getRequest()->getParam('options');

      // Prepare helper and params
        $viewHelper = Mage::helper('catalog/product_view');


        $params = new Varien_Object();
        $params->setCategoryId($categoryId);
        $params->setSpecifyOptions($specifyOptions)


        // Render page
        try {
            $this->_forward('noRoute'); return;
            //$viewHelper->prepareAndRender($productId, $this, $params);
        } catch (Exception $e) {
            if ($e->getCode() == $viewHelper->ERR_NO_PRODUCT_LOADED) {
                if (isset($_GET['store'])  && !$this->getResponse()->isRedirect()) {
                    $this->_redirect('');
                } elseif (!$this->getResponse()->isRedirect()) {
                    $this->_forward('noRoute');
                }
            } else {
                Mage::logException($e);
                $this->_forward('noRoute');
            }
        }
    }
}

No comments:

Powered by Blogger.