Magento – Magento 1: model rewrite vs event dispatching, best strategy

event-observermagento-1magento-1.9moduleoverrides

I'm working on a module where I need to modify the behavior of the getTracking() method in a shipping method carrier model. For example let's take this default one: Mage_Usa_Model_Shipping_Carrier_Dhl

My requirement is to modify the tracking result returned by this method.

I have two solutions in mind but I'm not sure if one is better or the other (or maybe there's a 3rd solution even better )

Solution 1: classic rewrite

Rewrite the model and the method and add my custom modification before the return statement.

The code would look like this:

public function getTracking()
{
    $result = parent::getTracking();
    // My modifications here
    return $result;
}

Solution 2: rewrite and event dispatched

Rewrite the model and the method. Get the original result with parent::getTracking, dispatch a custom event and return the result. Use an observer to modify the results.

The code would look like this:

public function getTracking()
{
    $result = parent::getTracking();
    Mage::dispatchEvent('my_custom_event', array('result' => $result));
    return $result;
}

To me, the second solution is better but I don't feel good using rewrites.

So my questions are:

  • Which one of those solutions is the best ?
  • Is there a dynamic event I'm not aware of I could observe instead of doing all this ?
  • Any other suggestions ?

Best Answer

IMHO it depends on what you are going to do:

1. One time quick and dirty code:

If your code remains inside a single project and you will be the only one handling it, then a single rewrite can be a good idea since I do not see any good reason to increase code complexity with an observer.

2. Reusable code:

If you are going to create something like a community extension, then adding an observer could be a good idea since it gives the possibility to other people ti interact with it.

Related Topic