Magento – Keeping module compatible for different Magento versions

magento-1moduleversion

Today, I am running into the following problem:
A module I developed works very well in a Magento 1.7 version store.
Now, I need to adapt it to also work with a Magento 1.5 store.

One point at which the compatibility runs apart is in my collection where I am exending the class Mage_Core_Model_Resource_Db_Collection_Abstract. This class does not exist in Magento 1.5, but it has some nice functionality like getMainTable().
One thing I could do is to instead use the class Varien_Data_Collection_Db which is inherited from in Mage_Core_Model_Resource_Db_Collection_Abstract.
This works, but then I cannot use the getMainTable() method anymore – even not in the 1.7 store where it actually exists.

How do you handle such version specific quirks?
It seems absurd to write a custom class which implements the stuff version 1.7 already has and thereby duplicate code in that version.
On the other hand, it is bad not to have the function and use worse coding habits like hard-coding instead.
So, is there any good approach in writing Magento modules which are backwards-compatible?

Best Answer

You could create an intermediary class that implements all the functions that you require and depending on the version of magento call parent's implementation or use your own implementation:

model/Int.php

<?php
  if (!version_compare(Mage::getVersion(), '1.7', '>=')) {
    class N_M_Model_Int extends Mage_Core_Model_Resource_Db_Collection_Abstract
    {
    }
  } else {
    class N_M_Model_Int extends Varien_Data_Collection_Db
    {
      public function getMainTable()
      {
        // my implementation
      }
    }
  }
?>

model/Final.php

<?php
  class N_M_Model_Final extends N_M_Model_Int
  {
    // common code between all the versions
  }
?>
Related Topic