How do i override Mage_Core_Controller_Request_Htt

2019-04-14 18:10发布

问题:

I have made some changes to Mage_Core_Controller_Request_Http but in the file distributed by with magento. This is not the best way, i know, but i have not been able to work out how to override a file in the Controller directory. I can find out how to override files in the controllers directory.

Can anyone tell me how i can override Mage_Core_Controller_Request_Http in my own extension.

thanks

回答1:

If you don't want to revert to the include path hack, you can also use reflection to set your own request class on the Mage_Core_Model_App model. You can use an observer for controller_front_init_before event for that.
I'll assume you are familiar how to create an event observer, soI'll only add the code for the observer method. If you need additional information please ask.

// Observer method
public function controllerFrontInitBefore(Varien_Event_Observer $observer)
{
    $app = Mage::app();
    $reflection = new ReflectionClass($app);
    $property = $reflection->getProperty('_request');
    $property->setAccessible(true);
    $myRequest = new Your_Module_Controller_Request_Http();
    $myRequest->setOrigRequest($app->getRequest()); // if needed
    $property->setValue($app, $myRequest);

    // Proof of concept:
    // Loggs Your_Module_Controller_Request_Http
    Mage::log(get_class(Mage::app()->getRequest()));
}

Create the class Your_Module_Controller_Request_Http and extend the original Mage_Core_Controller_Request_Http.
After that event your request object will be used instead of the original.

This enables you to stay as upgrade safe as possible, because you do not have to copy over the full class from the cor code pool.



回答2:

Edit: Vinai's solution is the better one.

Because this class is instantiated directly, you will have to use the so-called include path hack to override.

The order of precedence for include paths which affect Varien_Autoload's work is set in app/Mage.php. That order is as follows:

  1. app/code/local/
  2. app/code/community/
  3. app/code/core/
  4. lib/

Therefore, if you copy your file to an analogous path under the local or community codepools, your definition of that class will be used.



回答3:

Since Magento 1.7 you can use the method Mage::app()->setRequest($request) to replace the request object within an observer for the controller_front_init_before event as suggested by Vinai.

WARNING for Magento Enterprise: The Full Page Cache won't work with this method, as it relies on changes to the request object done before controller_front_init_before. You either need to manually copy all properties from the old request to the new - or replace the request class with benmarks solution.