How to Change Magento 2 Functionality 03/10 | Magento 2 Tutorials for Beginners (2019) | MageCafe

Codilar www.youtube.com

Brief Summary

This video explains how to modify Magento's core functionality without directly altering the core files, which is crucial for maintaining upgrade compatibility. It covers three primary methods: plugins, events/observers, and preferences, outlining their use cases and providing practical examples. The video emphasizes using plugins as the preferred method, followed by events/observers, and finally, preferences as a last resort.

  • Plugins: Best for modifying public methods.
  • Events/Observers: Useful when plugins can't be used.
  • Preferences: A last resort for changing class behavior.

Introduction

The video addresses the common need to customize Magento's functionality and highlights the dangers of directly modifying the core code. Direct modifications can be overwritten during Magento upgrades, causing loss of functionality. The tutorial introduces three methods to safely alter Magento's behavior: plugins, events/observers, and preferences.

Demonstration Setup

The presenter sets up a demo Magento store with sample products and a custom module. The goal is to modify the product names on the listing page based on their price: products under $70 will have "so cheap" appended to their name, while those over $70 will have "so bloody expensive" added. The video starts by illustrating the incorrect approach of directly changing the core files.

What Not to Do: Direct Core Modification

The video shows the temptation of directly modifying the getName function in the Product.php file within Magento's core catalog module. By changing the function to return "blah blah," the presenter demonstrates how easy it is to alter the displayed product names. However, this approach is strongly discouraged due to the risk of losing changes during upgrades.

Safe Modification Methods: Plugins, Events, and Preferences

The video introduces three safe methods for modifying Magento's functionality: plugins, events/observers, and preferences. Plugins are the preferred method for modifying public methods of classes. Events and observers are used when plugins are not suitable. Preferences are considered a last resort when other methods fail.

Plugins Explained

Plugins can modify public methods of classes, with three types available: "before," "after," and "around." "Before" plugins execute before the original method, "after" plugins execute after, and "around" plugins execute both before and after. The "around" plugin uses a callable method to control the execution of the original function. For the product name modification, an "after" plugin is chosen to append text to the existing name.

Implementing a Plugin

The presenter creates a di.xml file in the module's frontend area to register the plugin. The type name attribute specifies the class to be modified (Magento\Catalog\Model\Product), and the plugin name and type attributes define the plugin's class and name. The plugin class (Codilar\Demo\Plugin\Product) contains the afterGetName function, which takes the product object and the original name as parameters, appends the appropriate text based on the price, and returns the modified name.

Testing the Plugin

After implementing the plugin, the product names on the listing page are updated to include "so cheap" or "so bloody expensive" based on the product price, demonstrating the successful modification of the core functionality using a plugin.

Events and Observers Explained

Events and observers allow intercepting Magento's flow by "observing" events fired during the application's execution. For example, the customer_login event can be observed to trigger actions after a customer logs in. In this demonstration, events and observers are used to modify product names, similar to the plugin example.

Implementing Events and Observers

The presenter identifies the catalog_block_product_list_collection event, which is fired after the product collection is initialized. An events.xml file is created to register an observer for this event. The observer class (Codilar\Demo\Observer\Product) implements the ObserverInterface and contains the execute function. This function retrieves the product collection from the event data, iterates through the products, and modifies the names based on the price.

Testing Events and Observers

After implementing the event and observer, the product names are again updated to include "so cheap" or "so bloody expensive," demonstrating the successful modification using events and observers.

Preferences Explained

Preferences allow replacing a class with a custom class. When Magento creates an object of the original class, it will instead create an object of the preferred class. This method can change almost any functionality in Magento.

Implementing Preferences

A preference is set in the di.xml file, mapping the Magento\Catalog\Model\Product class to a custom class (Codilar\Demo\Model\Product). The custom class extends the original product class and overrides the getName function. The overridden function calls the parent's getName function to get the original name and then appends the appropriate text based on the price.

Testing Preferences

The product names are updated once more, demonstrating the successful modification using preferences. The presenter reiterates the order of preference for these methods: plugins, events/observers, and preferences.

Conclusion

The video concludes by summarizing the three methods for modifying Magento's core functionality without directly altering core files. Plugins are the preferred method, followed by events/observers, and preferences as a last resort.

Summarize any YouTube video in seconds

Get summaries like this one for any video, in your language, with the free Summ app.

Download on the Apple Store
Get it on Google Play

Transcript

Full transcript of “How to Change Magento 2 Functionality 03/10 | Magento 2 Tutorials for Beginners (2019) | MageCafe”. Click a timestamp to open the video at that moment. Need another video? Use the YouTube transcript generator.

0:04 hey guys this is joy from hotel our technologies and for today's tutorial what we are going to discuss is how to make changes to Magento score functionality without actually touching Magento Scone or actually directly touching it at least so what does this mean so many times we might be faced with a situation or a scenario where we have to change the functionality of how Magento handles his data or how much on to displays its data and at that situation it's a very bad practice to actually go ahead and change Magento score directly because let's say we change the Magento score directly and at a later point of time we are upgrading or Magento version so at that time whatever changes we made to our Magento code inside the Magento Skjold folder would just cease to exist and our code would not work again so that's why in

0:49 today's lesson I'm going to show you a couple of tricks and tips which Magento has provided us to make changes to these core functionalities of Magento without actually touching the Magento school so without wasting for the time let's get started alright so as you can see I have my demo store set up with all of the demo products and I also have my IDE set up so I also have made a module as you can see it's just a black model it has nothing as of now and for today's task let's say what we do is so all these products in the product listing page has some name which is being displayed in it right so this name is coming from a model probably and what we are going to do is let's say if the price of that product is less than let's say 70 if the

1:37 price of the product is less than 70 then we are going to say so cheap we're going to write so cheap along with the name and if the price of the product is greater than 70 then we are going to write so bloody expensive or something so as you can see this is a change in the functionality of how much info works right so this name is probably being returned by some morning and we are making some changes to this so how do we do that so firstly what I'm going to show you is what not to do in this scenario so I'll just go here and I did a little bit of snooping around with the Magento scored and what I found out is this name of the product is being displayed from the product or PHP which is inside the model folder of the catalog module so I'll just open that file and inside

2:24 this file if I go to how to search for it if I go to get name so as you can see there's a function called get name and as the name suggests this get name function returns the name to this page and it just displays the name of each of the products so let's just test this I'll just comment out this line and what I'm going to do is I'm gonna return something like let's say blah blah here all right so now if i refresh this I'm just gonna have to clean the cache so then / - clean sorry

3:10 bin / Magento cache clean yeah so now if i refresh go ahead and refresh this what I'm gonna see is all of these products would return the blah blah which I had just written from that get name function so sure enough all the products are returning blah blah for now so it's a pretty simple concept right you can just come here and instead of blah blah we can write whatever logic we want to write here like we can get the price and we can return so cheap or so bloody expensive along with this and that would work right that would show up here so that's our job done but that's exactly

3:56 what I told you not to do because that's a very bad practice because this file is inside the Magento score folder and we never ever ever change the Magento spawn folder and I explain to you why right so what to do then we cannot change this file so we're stuck so what else can we do so I'm just gonna show you a couple of things which Magento has given us to do this thing so the first thing which we can do is we can use something called preferences and the second thing is we use something called event and observers and the final thing is we use something called plugins which was introduced in Magento coolest and was not there in the length of one so what are these three things so I'll start with plugins so plugins are by far the best way to make any changes to Magento

4:43 score functionality so if we are in a situation where we can use the plugins to make some changes blindly just use the plugins you don't have to think about anything else the second thing is events and observers so there are a couple of things couple of situations in which we can't use the plugins so in that in those situations we can use the events and observers so what I'll write here is if the games fail and finally the Preferences so preferences are you can see a little bit of dirty way to do the changes in Magento but still it's better than making the changes too much into school folders directly so this you can say we have to use this if everything else fails and then I'm just gonna give us an smiley so yeah in all seriousness so

5:28 this is the sort order in which we have to use so whenever you use plugins we can use plugins we should use plugins at every point of time there are some situations where we cannot use plugins I'm going to tell you about those situations right now so in those situations we have to use events and observers and finally when both of these fail then we always have preferences and using preferences you can count on me that we can make changes to almost any functionality much into has to offer so let's start with plugins them so what are plugins so plugins you can say in short is a brilliant way to actually make changes to all of the public methods of all of the classes so in this scenario we'll take the product or PHP class for an example so keep it in mind that only public methods can be modified

6:14 using the plugins so protected as well as private methods cannot be unfortunately modified using plugins so how does the plugins work exactly so first I'm going to show you what are the types of plugins which Magento has made us made available so one is the before plug-in one is after and the third one is around so there are three types of plugins which we can use in Magento 2 so what are these three types of plugins so the p4 plugin right name such as is executed right before the actual function so if you are writing a function forget name so this before plug-in would be executed right before the actual function which is this get name is executed same with after the after is executed right after the actual function is executed and finally the around which is a little bit tricky so the around plugin is executed both

6:59 before as well as after the actual function is executed so how does that work so basically what happens is inside our round plug-in what we have is a conical method so let's say we call it dollar C so this round plugin takes a callable parameter a callable variable as a parameter so let's say we have gamma C for example so what is this colorful method so that callable method would be the actual function which we wrote that around looking for so let's say this is our plugin so we will have the dollar C here so wherever we count on let's see like this we have a variable called the function and we can take the response so this response would have whatever response this getname function or whatever function we are

7:46 adding the plugin for is returning so using this around before and after plugin we can make changes to a lot of core functionalities of Magento so for our example which is to make changes to the actual name of the products what I think is the after plugin would be the most suited because we can take the actual data from the get name function and then we can just append using our own logic we can append so cheap or so bloody expensive on top of it and we can this return that and that would get displayed here so we've decided that we will use the after plugin but how do we make the plugin so I'll come back to my module which is the coding our demo Motty which which we saw earlier so here inside the TC folder I have created a directory called front-end because that is the scope in which our plugin will be

8:31 executed and inside front-end we have a di dot XML file so this di dot XML file actually registers our plugin on top of this Magento's product PHP class so how does that work so here you can see we have the type name is equal to Magento catalog model product so that means that the product function is in the product class is the class for which we are writing a plug-in for and inside that we have the plug-in name is equal to so this can be anything for this example as a store plugin for product name and the type would be the class which has the function which we want to use as the plugin so in this scenario we have chordal our demo plugins and products so all this keep it in mind to put your plugins inside some folder called plugins or plugin to keep it organized so I just created a

9:18 directory called plugins and all my presence would be present here so for this example we have the product or PHP so this is the class it's a very simple class we just have the name space in the product inside that since we are writing a plugin for the get name function and it is an after plugin so here the name of the plug-in would be the function would be after get name so that's it after followed by whatever the name of the function we are adding the plug-in for us so there would be two parameters which the after after plug-in takes so the first parameter is an object of the class so this is the class so an object of the class for which we are adding the plug-in so that is the first parameter so I as you can see I took it in the normal called variable continent product and the second parameter is the name I mean is the variable which or the data

10:05 which this function is returning so whatever data this function returns would be the second variable in the after plugin so we have the name since it's returning the product name I think it's fair to call it dollar name so here I just wrote my logic if we just get the price from product product of get at a price then if the price is less than 60 i just appended so cheap on top of the name and if it is greater than 60 or equal to 60 then i just offended so bloody expensive and then i'm finally returning the name variable so that could make return the name of the product by appending whatever you want appended using our knowledge so now if i refresh this page what we should see is the so cheap or so bloody expensive being upended on top of this actual name

10:51 of the product using our plugins so as you can see sure enough we have so cheap so cheap and so bloody expensive since it's equal to 60 and like that we can see all of the product names have been changed so we successfully changed the core functionality which is changing the name of the product using plugins in the second way we'll be experimenting with the events so next we come to events and observers so what are events our observers so basically events and observers are a way to intercept Magento's flow so whatever Magento's flow is we can intercept the regular flow of Magento by inserting or you can say observing some of the events which much interference

11:37 so Magento fires a lot of events in between its flow and wherever we let's say there's an event for called customer underscore login so this event will be fired whenever customer log set so if we observe this event in our own Observer we can write some logic to change some of the functionality in which what should happen after login so for example we can use this event to write a function or write an observer to send an email to the customer when he logs in or something like that you get the point right so for this example is again we're gonna I just reset it my plugin so we have the actual name again so using events and observers what we're gonna try to do is the same thing we're going to append the name names of the products with so cheap or so bloody expensive using events so after doing a little bit

12:24 of research on how much into displays the products I found out that inside the catalog model we have the block and inside that we have product and here we have the list product or PHP so this is the you can say this is the block which is responsible for rendering all of these products so it just renders the product collection you can say so if I just search for event here so as you can see here in the function let me just scroll a little bit up so in the function initialize product collection we can see just at the end after getting the product collection and doing all the manipulations to the product collection an event is being fired where the collection is being passed so the name of the event is catalog block product

13:10 list collection so if we listen to this event we can modify this collection right before it's returned so that we can the name of the product with whatever we want to offend it so if we come back to our model so inside the ATC in and the front end as you can see I have created another file called event start XML so this events not XML has the event declaration so this basically this three lines basically means that for the event catalog NOC product list collection I want to observe and this is just like the plugins we can have any name we want it's just for identification purposes so the instance is the name of the class where our observer is there which class will observe this event so we have po dealer demo observer product so inside the observer directory as you can see we have a product or PHP file so this

13:56 product or PHP file is an end of pretty simple file it just implements the observer interface and since its implements the observer interface we have to write this function the execute function which takes the observer as a parameter so inside the observer we will get the data for this example we are getting the collection inside the observer so this collection is actually the name of the key which is being passed as the data so this can be product this can be customer depending on which event we are observing so this example we have the collection and we're just running a for each inside the collection and here we are adding the pretty same logic again if the price is less than 60 just append so cheap and if the price is greater than 60 or equal to 60 just right so bloody expensive on top of it and then we're just setting the data again and then whatever the collection is is modified and finally if

14:43 i refresh this page I should be able to see so cheap and so bloody expensive again appended to the names of the products using observers so let me just wait for it to reload and yes sure enough we have so cheap and so bloody expensive appended to the names of the products and this time we use events or observers to do it so finally we are going to see how we can use preferences so finally we're going to use preferences to do the same tasks so what are preferences so we figured out that plugins will be executed before after now around every function and events and observers will be or you can say observers will be hooked to all the events inside functions preferences basically means that we want to execute our own so let's say

15:30 there's a function called product right so there's a I mean there's a class called product sorry so it's a class called product and let's say this is present inside some directory called Magento and here we have a product or PHP file so let's say instead of this fine whenever someone creates an object of the class product we want to call it from a directory called code alert slash product of PHP and we want to call this file and the class inside this file so preferences allow us to do that so basically what preferences will do is whenever some object of this class is created it will check if any preferences are there for this class and if any preference is there so instead of calling this file it would call this file and it would load the class inside this file so using that we can pretty

16:15 much change almost all the functionality of Magento because we can change all of the classes or we can add references to all of the classes and we can change the functionality as we wish inside our own class right so I will show you how that works so firstly so this is the class we want to make a preference for right so this class is Magento catalog model product the namespace and the class name so if we come back to our model so here inside a TC front end and di XML you can see I wrote something like so the first one is for the plugin so we can ignore that for now so here you can see I wrote something like reference for and time we can write it in the same line as well there's a preference for and type so far means for which class do you want to set up reference and type means what is the

17:01 preference so basically what this line tells Magento is that the Magento catalog model product is the class and whenever someone creates an object or tries to create an object of this class do not do that instead of that create an object of code in our demo model product class so if we come to the code in our demo model and product of PHP so this is also you can see it's a pretty simple class so it has the namespace for dinner demo model and the class product so you can see I just extended the actual product model which we have a preference for the reason I did that is because if I don't do that and I have to all of the function because all of these functions all of these lines are necessary for this class to work so if I

17:47 am writing a preference I need to either write either I need to copy and paste all of those things or a much more simpler way to do it is using inheritance in which I just extended the actual parent class and then I can just change whatever function I want to change so for our example we want to change the get name function so inside that name I am just first calling the parent get name so that would execute this classes get name function and get the actual name of the product and then I am writing applying some of my own logic here the same thing I'm just getting the price and then if it's less than 60 append so cheap if it's greater than 60 append so very expensive and then return the final name so that would just return the appended name to the page and it would just display that so

18:34 basically what's happening is whenever this class I mean an object of this class is being created or magic was trying to created the DI XML tells Magento that don't create the class I mean the object from this class instead of that created from this class and that is what is happening so that this get name function is being overwritten and if we refresh this we can see that using preferences we can change the functionality of Magento and the name could be appended with so cheap or so bloody expensive depending on the friends so if I just wait for it to be or yeah so you can see it there so cheap and so very expensive again kemah and that is coming using references so we successfully used references events observers as well as plugins to do this

19:19 pretty much the same thing and like I mentioned earlier plugins are the best way to do it and whenever you cannot use plugins because let's say the method is private or protected we can look for events because if the events are being dispatched from there then we can modify the objects or the classes or whatever functions using events and observers and finally if both of them fail we always have preferences we can use preference to preferences to change almost all classes and almost all functionalities so that's all for today so I hope you enjoyed our watching the tutorial

Share

More video summaries