Using Preferences in Magento 2
Firstly, let us note that preferences are destructive.
That means to say that you tell the Magento system to use your class instead of the original one. It is akin to a rewrite in Magento 1 and doing such things can make it difficult to other module developers to make changes in the same area of code. Nevertheless, there are use cases for it and an example of one is when you need to add additional functionality to a class that currently does not exist.
The breadcrumbs block does not have a getCrumbs() method and I wish to add this to allow me to fetch the crumbs later on.
I would argue that this would be useful to have in the core code anyway but this is what we have for now.
You start by telling Magento to use your block class;
Inside your module /etc/frontend/di.xml:
This tells Magento that every time the class
Magento\Theme\Block\Html\Breadcrumbs is called, use my instance (
Something I like to do when preferencing a class is to follow the structure of the original.
In this case, I take everything after the [Vendor] part (Theme\Block\Html\Breadcrumbs) and then use that path in my own module.
Next, let’s actually create our new class
This is fairly self explanatory.
You only have to look in the parent class to know that the crumbs are stored in the _crumbs var.
Wait, why am i also overwriting the _toHtml() method.
Well, as a consequence of our preference Magento now tries loading the template file from our new module.
This is not what we want.
I still want the original template to be used so you have to reset the module name.
Code is available on github
Like this post? Share it :)