Class rewrites were, in many ways, that killer developer feature of Magento 1. Killer as in “Woah, awesomely powerful thing PHP developers don’t normally get to do”, and killer as in “Oh crud, we’ve killed the site with too many rewrites that are conflicting with each other”.
One of the promises of Magento 2 was a better rewrite system — with tools to help work around rewrite conflict problems. As of the dev51 release, Magento has two systems competing to replace rewrites. I wouldn’t be surprised to see one phased out completely, nor would I be surprised if both make it into final release.
The new system is Magento Plugins. I haven’t implemented one yet, but from what I see plugins provide a way to have your custom code fire before, after, or during any method call on a Magento object manager class.
The old system, class rewrites, is a simple duck typing system where developers can replace the instantiation of a Magento object manager class with their own class, and then change method definitions entirely. This old system has gone through many changes in the life of Magento 2. At some point in the late dev40s or early dev50s, it underwent another change.
If you want to rewrite a class in Magento 2, you can do so by placing the following nodes in a etc/di.xml
module configuration file
File: app/code/Packagenmae/Modulename/etc/di.xml
<config>
<preference for="MagentoCoreModelOld" type="PackagenameModulenameModelNew" />
<preference for="MagentoCoreModelOld2" type="PackagenameModulenameModelNew2" />
</config>
That is, dependency injection code has been moved into an individual di.xml
configuration file. Magento will ignore the old <global/>
level <di/>
node in config.xml
.
Additionally, support for the old <preferneces/>
node has been removed. Attempts to use it will result in an error (yay for configuration validation!). Instead, individual <preference/>
nodes should be used, as above. The for
attribute contains the old class name (the one you’re rewriting). The type
attribute contains the new class you’re rewriting to. This change looks like it came about, in part, due to Magento 2’s new full embrace of PHP namespaces. The backslash character isn’t a valid XML node name character, so the following is invalid XML
<!-- invalid, don't use -->
<config>
<preferences>
<MagentoCoreModelOld>PackagenameModulenameModelNew</MagentoCoreModelOld>
</preferences>
</config>
There’s probably more changes to come — life on the bleeding edge requires bandages.