Magento: Avoid Module/Extension Rewrite/Override Class Conflict

While developing Magento modules/extensions, we often come up with a case where our module and some other module are rewriting/overriding the same core class. Hence, we get a conflict here and either our module or the other module will not function as expected.

There are some ways to avoid such conflicts. I will explain about two ways to do so.

1) By Editing Module Configuration XML

Suppose, YourNamespace_YourModule and OtherNamespace_OtherModule are overriding the same core class.

– Go to app/etc/modules/ directory
– Open YourNamespace_YourModule.xml file
– Add depends node as below:


<config>
    <modules>
        <YourNamespace_YourModule>
            <active>true</active>
            <codePool>community</codePool>            
            <depends><OtherNamespace_OtherModule /></depends>
        </YourNamespace_YourModule>
    </modules>
</config>

– Now, YourNamcespace_YourModule will be loaded after OtherNamespace_OtherModule. So, now you can incorporate other module’s changes in your module’s class and make both modules work.

2) By Extending the Conflicting Class

Suppose, you have the following two custom module classes:

YourNamespace_YourModule_Model_Product extends Mage_Catalog_Model_Product

OtherNamespace_OtherModule_Model_Product extends Mage_Catalog_Model_Product

You can see that both modules’ (YourNamespace_YourModule and OtherNamespace_OtherModule) Product model class extends Mage_Catalog_Model_Product. In this case, Magento will be addressing one of the modules class only.

We can check if one of the module class exists or not. And, then adjust the parent class name. Here is how we do it:

Let’s edit YourNamespace_YourModule class.


/** 
 * We don't need to check class name 
 * if both modules (YourNamespace_YourModule and OtherNamespace_OtherModule) are enabled
 * 
 * Checking this to make sure that we don't get any error 
 * when OtherNamespace_OtherModule is disabled
 */
if (!@class_exists('OtherNamespace_OtherModule_Model_Product')) {	
	class OtherNamespace_OtherModule_Model_Product extends Mage_Catalog_Model_Product { }
} 

/**
 * YourNamespace_YourModule extends OtherNamespace_OtherModule
 * and OtherNamespace_OtherModule will already be extending the core class
 */
class YourNamespace_YourModule_Model_Product extends OtherNamespace_OtherModule_Model_Product

Hope this helps.
Thanks.