How to redirect in controller by throwing an exception

Posted 7 months ago. Visible to the public.

This whole class Mage_Core_Controller_Varien_Exception has only one reference in the core, see search result Show archive.org snapshot .

In the catch, there is a way to redirect or forward or call another action. So how do we make this works? Here's an example:

class Sxxx_Mohe_Model_Observer_Catalog
{
    /**
     * Event 'catalog_controller_category_init_after'
     * @see Mage_Catalog_CategoryController:: _initCategory()
     *
     * Redirect category view to product view if customer has Product ID.
     *
     * @param Varien_Event_Observer $observer
     */
    public function categoryInitAfter($observer)
    {
        /** @var Mage_Catalog_Model_Category $category */
        $category = $observer->getCategory();
        if ($category->getName() === 'My Product') {
            $customer = Mage::getSingleton('customer/session')->getCustomer();
            if ($pid = $customer->getProductId()) {
                /** @var Mage_Catalog_CategoryController $controller */
                $controller = $observer->getControllerAction();
                /**
                 * Prevent setting param 'id' to category ID. Required only if forward.
                 * @see Mage_Core_Controller_Varien_Router_Standard ::match() $request->setParam()
                 */
                $controller->getRequest()->setRequestUri();
                $controller->getRequest()->setPathInfo();
                
                /**
                 * Prevent Mage_Core_Exception: Mage registry key "current_category" already exists
                 * @see Mage_Catalog_Helper_Product ::initProduct()
                 */
                Mage::getSingleton('catalog/session')->unsLastVisitedCategoryId();

                /**
                 * Differences between forward and redirect: forward uses the existing URL, redirect uses the target URL.
                 * Inspired from:
                 * @see Hackathon_HoneySpam_Model_Observer
                 * How it works:
                 * @see Mage_Core_Controller_Varien_Action ::dispatch()
                 */
                $e = new Mage_Core_Controller_Varien_Exception();
                $e->prepareForward('view', 'product', 'catalog', ['id' => $pid]);
                /*
                $e->prepareRedirect(
                    Mage::getResourceSingleton('core/url_rewrite')->getRequestPathByIdPath("product/$pid", Mage::app()->getStore()->getId())
                ) // Cost one DB request.
                */
                //$e->prepareRedirect('catalog/product/view', ['id' => $pid]); // Exposes product ID in the browser.
                throw $e;
            }
        }
    }
}
kiatng
Last edit
6 months ago
kiatng
Posted by kiatng to OpenMage (2023-11-02 01:19)