Demac Media Demac Media Brand Demac Media Brand

Blog

Subscribe

#RealMagento: Create a Basic Magento 2 Plugin + Lesson Plan

Timer Icon 8 Mins

Development, Magento Commerce

Six months ago Magento 2 launched much to our delight! Our CEO, Matt Bertulli, covered the November 2015 launch in detail on our blog. Since the big release our team of developers have been busy training on Magento 2 and learning the ropes of the brand new platform to continue bringing our retailers the very best in eCommerce solutions. The Demac Media development team have always been key contributors to the #RealMagento community since 1.X – we wrote the book on Magento! – and we plan to maintain the same level of excellence with Magento 2.

Fill in the Form Below to Download the Lesson Plan + Video Tutorial!

commerce, website design, demac media, magento 2 plugin, plugin creation, magento 2, new model resource, new plugin resource




In this tutorial I’ll be walking you through the steps to create your own plugin in Magento 2, broken down by first showing how to create a new module then creating a plugin. If you plan on teaching your team of developers how to do the same, I’ve even included a free downloadable lesson plan and video walk-through to assist you! Get your copy by filling in the form above! Thank you to Justin Liotta, another Certified Magento Developer at Demac, who helped me put all of this together.

How Modules Work in Magento 2

New Module Steps:

1. Create [ModuleName] folder in src/[Company Name Here]
src/Demac/LoginMessagePlugin
2. Create etc folder in [Company Name Here]/ModuleName
3. Create module.xml in etc folder
src/Demac/LoginMessagePlugin/etc/module.xml

Example module file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name=“Demac_WelcomePlugin" setup_version="0.1.0">
    </module>
</config>
</xml>

Note: See the xmlns lines parts of the config tag? These are the mappings that tell phpstorm where the definition data is. This helps you write your code with shortcuts and so on.

4. Create a regisration.php file in [Module Name]/registration.php. This file tells the Magento setup process that there is a new module that is available, equivalent to the app/etc/modules files in Magento 1

Example registration.php below:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Demac_WelcomePlugin',
    __DIR__
</php>

To check to see whether or not Magento 2 has registered the module run in your root folder from the command line “bin/magento module:status” This will give you a list of the modules on your project and all the modules that are not enabled

6. To enable it you will need to run bin/magento module:enable [ModuleName]
7. When prompted run setup:upgrade, the equivalent of having an install script that runs

WHY?

The Magento 2 Frontend is packaged with the module. Layout and templates exist in the module not in a separate design folder. This implies that modules are independent of Magento code and thus should be unaffected by major Magento upgrades

Now you have a module set up to work with. The next part. Making our plugin!

Creating a New Plugin

For this step I’m going to run you through an activity. Together we’ll create a Plugin that adds a customer welcome message after logging in order creating an account.

What is a Plugin in Magento 2?

They are a refined observer event handler. They can be called on any method making them more versatile.

How do they work?

Why use them over observers?

In our Example we will be creating a plugin that adds a custom success message after customer login or creation.

Steps To Create:

3. See example code below:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Model\Session">
        <plugin name="Demac_WelcomePlugin" type="Demac\WelcomePlugin\Plugin\WelcomePlugin" />
    </type>
</config>

Note the “type” tag. This determines which interface/model you will be working with. The plugin tag tells Magento what to call your plugin and the placement of your plugin class file

4. For our example we will create a Plugin folder in our [Module Name] folder and in that folder create a WelcomePlugin.php class

5. Declare your dependencies under your namespace using the references of the classes and interfaces you wish to use. You are basically importing a class. See below for examples.

6. Inside your class create a construct method that will create a Message Manager Interface for this class for you to use.

See Below:

private $messageManager;

public function __construct(MessageManager $messageManager){

    $this->messageManager = $messageManager;
}

7. For our example we need a class/interface that has a method we can use to determine whether or not a customer is logged in or not. You can search for your own, but the one I chose was SetCustomerDataAsLoggedIn in the Session class. And we will be adding the message after this has run so that we only get successful logins.

<?php

namespace Demac\WelcomePlugin\Plugin;

use Magento\Framework\Message\ManagerInterface as MessageManager;

class WelcomePlugin {

}
</php>

8. Inside your class create a public function that calls after the SetCustomerDataAsLoggedIn called afterSetCustomerDataAsLoggedIn. This method will need to have passed in as arguments/params the Session class and the result of that method.

It is important to add the $result into this method so that we can return it. Remember the after method manipulates the behaviour and output after the function has run. So if you don’t return the $result at the end (altered or unaltered) this whole process won’t work correctly

See below for example:

public function afterSetCustomerDataAsLoggedIn(\Magento\Customer\Model\Session $session, $result){
    $this->messageManager->addSuccessMessage("Don't forget to check out our latest line of death rays");
    return $result;
}

9. As seen in the code above I also used the Message Manager to add a Success message. This is the final part. Now check out your login page or create a customer and you should see your customer Success message showing up.

Do It Yourself!

Now try and create your own plugin. A suggested plugin would be to create a custom Notice Message for when a customer adds an item to the cart. If you get stuck please check out the video tutorial linked below where I go through the process step by step!

If you are planning on teaching this to your development team, don’t forget to download our lesson plan package below with the necessary teaching resources including walkthrough video tutorial of the activity:



commerce, website design, demac media, magento 2 plugin, plugin creation, magento 2, new model resource, new plugin resource

Subscribe to the Blog

Stay updated with 20,000+ eCommerce leaders in our community

Sign Up

Let’s talk about your 10X return

Icon/Social/Phone Contact us for pricing information