Magento 2 module development – a comprehensive guide – Part 3 (Observers)

In this article I will describe the following two topics:

  • Building up a basic sample module
  • Creating and implementing Observers

 

1) Building up a basic sample module

 

In my previous article (Part 1, Part 2) you could see how to make a sample Magento 2.0 module and how to create, edit, save and delete the database tables, admin grid and data belonging to it.

Now we are going to deal with the operation of observers within another simple Magento 2.0 module.

In the first step let’s create a basic sample module. Since I already described this topic in my earlier post, now I am presenting only the module structure.

 

magento 2 module structure

 

2) Creating and implementing observers

 

We create two Observers in the Magento 2.0 sample module that we “connect” with two separate events. In the case of Magento 1.x modules the functions (and business logics running in them), to be created with different events, were created in one Observer class.

In Magento 2.0, for every event we need to create a separate Observer class in which the business logic is created in the execute(…) function.

Before the Observer class is created, we need to define to which event your own business logic should apply. Here it’s important to decide which page you want to use it on, either on frontend or admin (adminhtml), so you need to place the definition xml file in the appropriate location.

You can place it “globally”, but I recommend placing it separately. In the first example, in case of a frontend page event, after sending the default Magento 2.0 contact form,      we want to “catch” the sent data with our own Observer class.

For this we need an events.xml file which can be found in the following location in our sample module: app/code/Aion/Sample/etc/frontend/events.xml. The file contains the following:

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_postdispatch_contact_index_post">
        <observer name="aion_sample_post_capture" instance="Aion\Sample\Observer\CapturePost" />
    </event>
</config>

The file’s structure is very simple. The events we’d like to “catch” are defined in the name parameter within the event tag. In our case it is the event following the post controller in the -default Contact module of Magento 2.0. Then we define our own Observer class, to be called in the future, in the Observer tag located within the event tag. We also give it a name parameter.

We can define more “custom” Observers in a list- with this same event, and we can define more event tags in the xml file if we want to use additional “custom” Observers.

Next, we need to create our own Observer class and define the necessary business logic in it. In our sample module, the file is located here: app/code/Aion/Sample/Observer/CapturePost.php. The file contains the following:

<?php
namespace Aion\Sample\Observer;

use Magento\Framework\Event\ObserverInterface;
use Aion\Sample\Helper\Data as DataHelper;
use Psr\Log\LoggerInterface;
use Magento\Framework\Event\Observer;
use Magento\Customer\Model\Customer;
use Magento\Framework\Exception\LocalizedException;

class CapturePost implements ObserverInterface
{
    /**
     * Aion Sample helper
     *
     * @var DataHelper
     */
    protected $_helper;

    /**
     * @var LoggerInterface
     */
    protected $_logger;

    /**
     * Capture Post Observer constructor
     *
     * @param DataHelper $helper
     * @param LoggerInterface $logger
     */
    public function __construct(
        DataHelper $helper,
        LoggerInterface $logger
    ) {
        $this->_helper = $helper;
        $this->_logger = $logger;
    }

    /**
     * Sample post capture event handler
     *
     * @param Observer $observer
     * @return self
     */
    public function execute(Observer $observer)
    {
        if ($this->_helper->isEnabled()) {

            $controller = $observer->getEvent()->getControllerAction();
            $post = $controller->getRequest()->getPostValue();

            if ($post) {

                try {

                    $this->_logger->debug('CapturePostObserver');
                    $this->_logger->log(100, print_r($post, true));

                    // comment out to check data
                    //\Zend_Debug::dump($post);
                    //die();

                    // do some logic

                } catch (LocalizedException $e) {
                    $this->_logger->error($e->getMessage());
                } catch (\Exception $e) {
                    $this->_logger->critical($e);
                }

            }

        }

        return $this;
    }
}

If the event, defined in the events.xml file mentioned above, takes place, the execute function in the CapturePost class is executed. The function first checks if our own module is enabled or not. If it is enabled, it “catches” the data posted by the default Contact form of Magento 2.0.

For simplicity’s sake, we only log the array in the debug.log file. With the data provided this way, we can create our own business logic.

In the second example, with an admin-related event, after the default Magento 2.0 customer save, we want to “catch” the customer object and data with our own Observer class.

For this, we’ll need an events.xml file which can be found in our sample module under app/code/Aion/Sample/etc/adminhtml/events.xml. The file includes the following:

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_postdispatch_contact_index_post">
        <observer name="aion_sample_post_capture" instance="Aion\Sample\Observer\CaptureCustomer" />
    </event>
</config>

 

 

The file structure is the same as with the events.xml described in the precious example, but this time the adminhtml directory is placed here, thus the defined CaptureCustomer class will be called only in the admin scope for the event of customer_save_commit_after.

 

Next, similarly to the previous example, we need to create our own Observer class and implement the necessary business logic in it.

 

The file is located in our sample module under app/code/Aion/Sample/Observer/CaptureCustomer.php. The file contains the following:

 

<?php
namespace Aion\Sample\Observer;

use Magento\Framework\Event\ObserverInterface;
use Aion\Sample\Helper\Data as DataHelper;
use Psr\Log\LoggerInterface;
use Magento\Framework\Event\Observer;
use Magento\Customer\Model\Customer;
use Magento\Framework\Exception\LocalizedException;

class CaptureCustomer implements ObserverInterface
{
    /**
     * Aion Sample helper
     *
     * @var DataHelper
     */
    protected $_helper;

    /**
     * @var LoggerInterface
     */
    protected $_logger;

    /**
     * Capture Customer Observer constructor
     *
     * @param DataHelper $helper
     * @param LoggerInterface $logger
     */
    public function __construct(
        DataHelper $helper,
        LoggerInterface $logger
    ) {
        $this->_helper = $helper;
        $this->_logger = $logger;
    }

    /**
     * Sample customer capture event handler
     *
     * @param Observer $observer
     * @return self
     */
    public function execute(Observer $observer)
    {
        if ($this->_helper->isEnabled()) {

            /* @var Customer $customer */
            $customer = $observer->getEvent()->getCustomer();

            if (!is_null($customer) && $customer->getEntityId()) {

                try {

                    $this->_logger->debug('CaptureCustomerObserver');
                    $this->_logger->log(100, print_r($customer->getData(), true));
                    // comment out to check data
                    //\Zend_Debug::dump($customer->getData());
                    //die();

                    // do some logic

                } catch (LocalizedException $e) {
                    $this->_logger->error($e->getMessage());
                } catch (\Exception $e) {
                    $this->_logger->critical($e);
                }

            }

        }

        return $this;
    }
}

 

If the event, defined in the second events.xml file mentioned above, takes place, the function in the CaptureCustomer class is executed. The function first checks if our own module is enabled or not. If it is enabled, it “catches” the customer object after the described save in Magento 2.0.

For simplicity’s sake, we only log the data of the object in the debug.log file. With the object and data provided this way, we can create our own business logic.

 

Summary

In this article we illustrated with the help of two examples how to define and create custom or unique modules in Magento 2.0, for different events on both the fronted and admin pages.

 

See also Part 1 (comprehensive guide), Part 2 (create admin grid) and Part 4 (Knockout JS).

 

 

126 replies
  1. Alida Mascagni says:

    Wonderful work! This is the type of info that are supposed to be shared across the net. Shame on Google for no longer positioning this post higher! Come on over and discuss with my site . Thank you =)

  2. Market manipulation says:

    This design is incredible! You certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  3. what is quantitative easing says:

    Heya just wanted to give you a quick heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same results.

  4. What is mass hysteria says:

    hello there and thank you in your information – I have certainly picked up anything new from proper here. I did alternatively experience several technical issues the use of this site, as I experienced to reload the web site lots of times prior to I may get it to load correctly. I had been brooding about in case your web host is OK? No longer that I am complaining, however slow loading circumstances times will sometimes impact your placement in google and can damage your quality score if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am adding this RSS to my e-mail and can glance out for much more of your respective fascinating content. Ensure that you update this once more soon..

  5. stock market close time today says:

    Somebody essentially assist to make critically posts I would state. That is the very first time I frequented your website page and to this point? I amazed with the analysis you made to make this actual put up extraordinary. Fantastic activity!

  6. bullish outlook says:

    What¦s Happening i’m new to this, I stumbled upon this I’ve found It absolutely helpful and it has helped me out loads. I’m hoping to give a contribution & assist other customers like its aided me. Great job.

  7. sanctuary cities in the us says:

    What i do not understood is in reality how you’re not actually much more well-appreciated than you may be now. You’re so intelligent. You realize therefore significantly in relation to this topic, made me personally consider it from a lot of various angles. Its like men and women are not interested until it?¦s one thing to accomplish with Girl gaga! Your personal stuffs great. At all times maintain it up!

  8. vitamins and supplements says:

    Howdy! Someone in my Facebook group shared this site with us so I came to check it out. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Terrific blog and outstanding style and design.

  9. comando torrents says:

    F*ckin’ amazing things here. I am very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you please drop me a e-mail?

  10. filmes via torrents says:

    I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I’m looking to create my own blog and would like to know wheere u got this from. thanks

  11. erjilo pterin says:

    I was recommended this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are wonderful! Thanks!

  12. erjilo pterin says:

    I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thanks again

  13. T-shirts says:

    It¦s in reality a nice and helpful piece of info. I am happy that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  14. Joker123 Online says:

    Very nice info and right to the point. I don’t know if this is really the best place to ask but do you guys have any ideea where to get some professional writers? Thank you :)

  15. Joker Net says:

    I like what you guys are up also. Such clever work and reporting! Carry on the excellent works guys I have incorporated you guys to my blogroll. I think it will improve the value of my web site :)

  16. Slot Joker says:

    Superb blog! Do you have any suggestions for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed .. Any recommendations? Bless you!

  17. venda de armas baratas says:

    Hi just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

  18. hospedagem de sites says:

    Nice blog right here! Also your website quite a bit up fast! What host are you the use of? Can I am getting your associate hyperlink for your host? I wish my site loaded up as fast as yours lol

  19. situs judi aduq qq online says:

    Thanks for every other informative web site. Where else could I get that type of information written in such a perfect means? I have a project that I am just now running on, and I’ve been at the look out for such information.

  20. Slotxo says:

    Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.

  21. aulas online says:

    I’m often to blogging and i really admire your content. The article has really peaks my interest. I’m going to bookmark your site and preserve checking for brand spanking new information.

  22. SMM Services says:

    I’m now not certain where you’re getting your information, however good topic. I must spend some time finding out more or working out more. Thanks for magnificent info I used to be looking for this info for my mission.

  23. sanchore rajasthan says:

    I know this if off topic but I’m looking into starting my own weblog and was wondering what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100 certain. Any recommendations or advice would be greatly appreciated. Many thanks

  24. gelato 47 says:

    Thank you, I’ve recently been looking for information about this subject for ages and yours is the best I’ve found out till now. But, what about the bottom line? Are you positive concerning the supply?

  25. my link says:

    There is noticeably a bundle to find out about this. I assume you made certain nice factors in features also.

  26. Hollow Board says:

    Whoa! This blog looks just like my old one! It’s on a entirely different topic but it has pretty much the same layout and design. Outstanding choice of colors!

  27. kittens for sale says:

    After examine a couple of of the blog posts in your website now, and I really like your approach of blogging. I bookmarked it to my bookmark web site list and will probably be checking back soon. Pls try my site as nicely and let me know what you think.

  28. Les Pti Tutos says:

    I¦ve been exploring for a little bit for any high quality articles or weblog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this site. Studying this information So i¦m happy to express that I’ve a very good uncanny feeling I discovered just what I needed. I such a lot indubitably will make certain to do not disregard this site and give it a look regularly.

  29. prognatismo says:

    I do not even understand how I ended up here, but I assumed this post was once great. I don’t know who you are however certainly you are going to a famous blogger for those who are not already ;) Cheers!

  30. Wadham College of Science says:

    Hi, I think your site might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

  31. marketing 1on1 firm says:

    It’s actually a nice and helpful piece of information. I’m glad that you shared this helpful information with us. Please stay us up to date like this. Thanks for sharing.

  32. this link says:

    Spot on with this write-up, I truly assume this web site needs much more consideration. I’ll in all probability be again to learn much more, thanks for that info.

  33. helpful hints says:

    I am usually to running a blog and i actually appreciate your content. The article has really peaks my interest. I’m going to bookmark your web site and maintain checking for new information.

  34. more about the author says:

    Wow, superb weblog structure! How lengthy have you ever been blogging for? you made blogging glance easy. The total glance of your website is magnificent, as neatly as the content material!

  35. related site says:

    Thank you for every other excellent article. Where else may anyone get that type of information in such a perfect means of writing? I’ve a presentation next week, and I am at the look for such information.

  36. car latest coating says:

    Interesting blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog jump out. Please let me know where you got your design. Cheers

  37. car engine coating says:

    Great post however I was wondering if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit further. Many thanks!

  38. thai restaurant home delivery near me says:

    hey there and thank you for your information – I’ve definitely picked up anything new from right here. I did however expertise a few technical points using this web site, as I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage your high quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my email and could look out for much more of your respective intriguing content. Ensure that you update this again very soon..

  39. video animation makers says:

    I’m not sure why but this site is loading extremely slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later and see if the problem still exists.

  40. best wordpress hosting says:

    Undeniably believe that which you stated. Your favourite reason seemed to be at the web the easiest factor to take into accout of. I say to you, I certainly get irked even as other people consider issues that they plainly don’t know about. You managed to hit the nail upon the highest as neatly as defined out the whole thing with no need side-effects , folks could take a signal. Will probably be again to get more. Thanks

  41. best wordpress hosting says:

    Great info and straight to the point. I am not sure if this is in fact the best place to ask but do you folks have any thoughts on where to hire some professional writers? Thanks :)

  42. Joker123 Gamming says:

    Spot on with this write-up, I truly suppose this web site wants much more consideration. I’ll probably be again to learn far more, thanks for that info.

  43. Joker123.Net says:

    of course like your web-site but you need to check the spelling on several of your posts. Many of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I’ll surely come back again.

  44. aduslot says:

    You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  45. kevin david business insider says:

    What’s Going down i am new to this, I stumbled upon this I’ve discovered It positively useful and it has helped me out loads. I am hoping to give a contribution & aid different users like its helped me. Good job.

  46. kevin david birthday says:

    Hey there, You have performed a great job. I’ll certainly digg it and for my part suggest to my friends. I’m sure they will be benefited from this web site.

  47. libid gel original says:

    Hello there, I found your blog via Google while searching for a related topic, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.

  48. Lynwood Argenti says:

    I just want to mention I’m new to blogging and certainly enjoyed your blog site. Likely I’m want to bookmark your blog . You actually have tremendous articles and reviews. Many thanks for sharing with us your web page.

  49. Download Slot Online says:

    What i do not realize is actually how you’re now not really a lot more smartly-appreciated than you may be right now. You’re very intelligent. You realize thus considerably when it comes to this matter, produced me in my opinion believe it from so many numerous angles. Its like men and women are not fascinated except it is one thing to accomplish with Woman gaga! Your personal stuffs excellent. Always maintain it up!

  50. Joker123 says:

    Hey! This is kind of off topic but I need some guidance from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about creating my own but I’m not sure where to start. Do you have any points or suggestions? Many thanks

  51. Joker388 Gamming says:

    Hi there! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in exchanging links or maybe guest writing a blog article or vice-versa? My blog goes over a lot of the same topics as yours and I think we could greatly benefit from each other. If you happen to be interested feel free to send me an email. I look forward to hearing from you! Terrific blog by the way!

  52. Daftar FafaSlot says:

    Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but other than that, this is wonderful blog. A great read. I will definitely be back.

  53. Slot Joker says:

    I have recently started a web site, the information you offer on this site has helped me greatly. Thanks for all of your time & work. “Yield not to evils, but attack all the more boldly.” by Virgil.

  54. Login Joker123 says:

    Hello, you used to write excellent, but the last several posts have been kinda boringK I miss your tremendous writings. Past several posts are just a little bit out of track! come on!

  55. Joker388 says:

    Its excellent as your other blog posts : D, regards for putting up. “It takes less time to do things right than to explain why you did it wrong.” by Henry Wadsworth Longfellow.

  56. Joker123 Gamming says:

    Good post. I learn something more challenging on completely different blogs everyday. It will always be stimulating to read content material from different writers and practice a little bit something from their store. I’d prefer to make use of some with the content on my blog whether you don’t mind. Natually I’ll provide you with a link in your internet blog. Thanks for sharing.

  57. VivoSlot Gamming says:

    Hey there just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same results.

  58. Joker123 Net says:

    I¦ve been exploring for a bit for any high-quality articles or blog posts on this sort of space . Exploring in Yahoo I eventually stumbled upon this site. Reading this information So i am glad to express that I have a very good uncanny feeling I found out just what I needed. I most undoubtedly will make sure to don¦t overlook this website and give it a glance regularly.

  59. AdahDGaudett says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  60. central de iluminação de emergência says:

    Thanks for one’s marvelous posting! I really enjoyed reading it, you will be a great author.I will remember to bookmark your blog and will eventually come back very soon. I want to encourage yourself to continue your great work, have a nice day!

  61. https://vnz.bz/ says:

    Hello there, I found your blog via Google while searching for a related topic, your site came up, it looks great. I’ve bookmarked it in my google bookmarks.

  62. ฟุตบอลหนังอัด says:

    Do you have a spam problem on this website; I also am a blogger, and I was curious about your situation; many of us have developed some nice procedures and we are looking to exchange methods with others, please shoot me an e-mail if interested.

  63. criminal lawyer best says:

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting videos to your blog when you could be giving us something informative to read?

  64. AhmedESkyers says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  65. criminal lawyer cases says:

    We stumbled over here different web page and thought I should check things out. I like what I see so i am just following you. Look forward to looking into your web page for a second time.

  66. Industry News says:

    It’s in reality a great and helpful piece of info. I’m satisfied that you shared this useful information with us. Please keep us informed like this. Thanks for sharing.

  67. site says:

    I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I’m looking to create my own blog and would like to know wheere u got this from. thanks

  68. article says:

    I appreciate, cause I found exactly what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a great day. Bye

Trackbacks & Pingbacks

  1. who has tylenol on sale

    Magento 2 module development – a comprehensive guide – Part 3 (Observers) – aionhills.com

  2. ciprofloxacin 500mg antibiotics walmart cost

    Magento 2 module development – a comprehensive guide – Part 3 (Observers) – aionhills.com

  3. viagra on line no prec

    Magento 2 module development – a comprehensive guide – Part 3 (Observers) – aionhills.com

  4. doctor7online.com

    Magento 2 module development – a comprehensive guide – Part 3 (Observers) – aionhills.com

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published.