Hello World, or how to build the first module in Magento 2.1.5

Read this post to find out how to easily build your first module in Magento 2.1.5. By way of example, let me show you how to create a module that displays a “Hello World” message. To do this, we’ll use actions and a controller.

Prepare

We’ll use Magento v. 2.1.5 for this job. Before starting, look at the following two points, which may also be helpful in this and other tasks related to working with Magento 2.

1. Disabling the cache

Disabling the cache is very helpful in the process of building a new module. This will save you the trouble of flushing the cache each time you make a change and want to see the effects of your work.

How can you disable the cache?

Admin → System → Cache Management → check all and disable.

2. Magento developer mode

Enable the developer mode to view all errors related to the production of new code.

How can you disable the developer mode?

Go to the root directory and run the command:

$ php bin/magento deploy:mode:set developer

Create a module

Key configuration

Unlike the first version, in Magento 2 you put all modules in appropriate namespaces in the “app/code” directory, e.g. “app/code/Foo/Bar”, so your first step will be to create files to register a new module:

1. Create appropriate folders:

– app/code/Unity

– app/code/Unity/Helloworld

The Unity directory is the namespace, while Helloworld is the module name.

Note! – if you don’t have a code directory, create one.

2. After you’ve set up the folders, create the module.xml file in the app/code/Unity/Helloworld/etc directory and place the code there:

<?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="Unity_Helloworld" setup_version="1.0.0"></module>
</config>

3. To register the module, create the registration.php file in app/code/Unity/Helloworld/directory and place the code there:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Unity_Helloworld',
    __DIR__
);

4. Open the terminal and, in the main magento directory, run the command:

$ php bin/magento setup:upgrade

To check if the module is installed correctly, in the Administration Panel go to:

Admin → Stores → Configuration → Advanced → Advanced, find the module and check its status.

Create a controller

1. First, define the router by creating the routers.xml file in the app/code/Unity/Helloworld/etc/frontend directory and use the code below:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="helloworld" frontName="helloworld">
            <module name="Unity_Helloworld" />
        </route>
    </router>
</config>

Magento urls are created as: <frontName>/<controler_folder_name>/<controller_class_name>

So in our example, it will be:

helloworld/index/index

2. Now create actions.  In Magento 2, each controller can have only one action (the previous version allowed multiple actions). Create the Index.php file in app/code/Unity/Helloworld/Controller/Index,and add the following code:


&lt;?php
 
namespace Unity\Helloworld\Controller\Index;
 
use Magento\Framework\App\Action\Context;
 
class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
 
    public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this-&gt;_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        $resultPage = $this-&gt;_resultPageFactory-&gt;create();
        return $resultPage;
    }
}

Create a block

In this section, create a simple block using the “getText” method that will return a string of Hello World characters.

1. Create the Helloworld.php file in app/code/Unity/Helloworld/Block, and add the following code:


&lt;?php
namespace Unity\Helloworld\Block;
 
class Helloworld extends \Magento\Framework\View\Element\Template
{
    public function getText()
    {
        return 'Hello world!’;
    }
}

Create layout and template files

In Magento 2, layout and template files are kept in the module’s view directory. A directory can have three subdirectories: adminhtml, base and frontend.

• adminhtml – used for the Admin Panel

• frontend – used for changes visible to the client

• base – has default files for the above directories

1. First, create helloworld_index_index.xml in app/code/Unity/Helloworld/view/frontend/layout, and add the code below:

&lt;page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="1column"&gt;
    &lt;body&gt;
        &lt;referenceContainer name="content"&gt;
            &lt;block class="Unity\Helloworld\Block\Helloworld" name="helloworld" template="helloworld.phtml" /&gt;
        &lt;/referenceContainer&gt;
    &lt;/body&gt;
&lt;/page&gt;

2. Next, create the helloworld.phtml template file in app/code/Unity/Helloworld/view/frontend/templates,and add the code to it:

&lt;h1&gt;&lt;?php echo $this-&gt;getText(); ?&gt;&lt;/h1&gt;

Look at the result.

At helloworld/index/index in your browser you should see the following page:

Our Experts
/ Knowledge Shared

19.11.2024

PIM + AI = Success / Optimizing PIM Systems With Artificial Intelligence

Artificial Intelligence

In today’s rapidly changing business world, managing product information has become one of the key challenges, especially for companies operating across multiple markets. Although artificial intelligence is a hot topic, much of the available material focuses mainly on theory or the distant future. We’re taking it a step further – below, we present...

Ilustracja przedstawiająca robota reprezentującego sztuczną inteligencję, otoczonego symbolami wyzwań i błędów w sztucznej inteligencji. Obraz zawiera pomarańczowy mózg, zepsutą żarówkę i cyfrowe piksele, symbolizujące dane i zagrożenia etyczne związane z awariami sztucznej inteligencji
30.10.2024

The Complex World of AI Failures / When Artificial Intelligence Goes Terribly Wrong

Artificial Intelligence

AI has revolutionized industries, offering impressive capabilities in efficiency, speed, and innovation. However, as AI systems become more integrated into business operations, it becomes evident that these tools are not without flaws. From minor glitches to significant ethical issues, AI failures highlight the fragility of these systems. Businesses must...

AI w optymalizacji łańcucha dostaw materiałów budowlanych
28.10.2024

Application of Artificial Intelligence in Optimizing the Supply Chain of Building Materials

Artificial Intelligence

Can artificial intelligence revolutionize the management of building materials supply chains? Learn how AI can help optimize demand forecasting, manage orders and inventory, minimize risks, and personalize customer offerings. Discover the future of AI in the construction industry. The supply chain in the building materials industry is a complex and...

Expert Knowledge
For Your Business

As you can see, we've gained a lot of knowledge over the years - and we love to share! Let's talk about how we can help you.

Contact us

<dialogue.opened>