MyPage is a personalized page based on your interests.The page is customized to help you to find content that matters you the most.


I'm not curious

Magento 2 Tutorial: Building a Complete Module

Published on 02 April 17
0
1

Magento is currently the largest open-source eCommerce platform in the world. Due to its feature rich and extensible code base, merchants with large and small operations all around the world have been using it for a wide variety of projects.

Magento 1 has been around for eight years, and its successor, Magento 2, was released at the end of 2015, improving weak points of the earlier version such as:

  • Improved performance
  • Official automated test suite
  • Better back-end UI
  • New, more modern front-end codebase
  • A more modular way to develop modules, with files contained inside the Magento code instead of being scattered all over the place
  • Reduced number of conflicts between modules trying to customize the same functionality
Magento 2 Tutorial: Building a Complete Module - Image 1

A little over one year down the road, and the improvement is visible, even though not all of the problems mentioned have been totally solved. Now it’s completely safe to say that Magento 2 is a much more robust piece of software than its predecessor. Some of the improvements present in Magento 2 are:

  • Unit and integration tests, including an official and documented way to create them for custom modules
  • Modules that are really modularized, having all of their files placed under one single directory
  • A richer templating system, allowing the theme developer to create an n-level template hierarchy
  • A series of useful design patterns adopted throughout the code, improving the code quality and decreasing probability of errors created by modules—These include automatic dependency injection, service contracts, repositories, and factories, to name a few.
  • Native integration to Varnish as a full page caching system, as well as Redis for session and cache handling
  • PHP 7 support
The learning curve for Magento 2, with all of these changes, has become even steeper. In this article, I intend to show you how to develop your first Magento 2 module, and point you in the right direction to continue your studies. Let’s get to it!
2
Prerequisites

It is important that you have a good understanding of the following technologies/concepts in order to follow the rest of this article:

  • Object-oriented Programming (OOP)
  • PHP
  • Namespaces
  • MySQL
  • Basic bash usage

From all of the above, OOP is probably the most important one. Magento was initially created by a team of experienced Java developers, and their legacy can certainly be seen throughout the codebase. In case you are not very confident about your OOP skills, it might be a good idea to review it before beginning your work with the platform.

Overview of Magneto 2's Architecture

Magento’s architecture was designed with the intent of making the source code as modularized and extensible as possible. The end goal of that approach is to allow it to be easily adapted and customized according to each project’s needs.

Customizing usually means changing the behavior of the platform’s code. In the majority of systems, this means changing the core code. In Magento, if you are following best practices, this is something you can avoid most of the time, making it possible for a store to keep up to date with the latest security patches and feature releases in a reliable fashion.

Magento 2 is a Model View ViewModel (MVVM) system. While being closely related to its sibling Model View Controller (MVC), an MVVM architecture provides a more robust separation between the Model and the View layers. Below is an explanation of each of the layers of a MVVM system:

  • The Model holds the business logic of the application, and depends on an associated class—the ResourceModel—for database access. Models rely on service contracts to expose their functionality to the other layers of the application.
  • The View is the structure and layout of what a user sees on a screen - the actual HTML. This is achieved in the PHTML files distributed with modules. PHTML files are associated to each ViewModel in the Layout XML files, which would be referred to as binders in the MVVM dialect. The layout files might also assign JavaScript files to be used in the final page.
  • The ViewModel interacts with the Model layer, exposing only the necessary information to the View layer. In Magento 2, this is handled by the module’s Block classes. Note that this was usually part of the Controller role of an MVC system. On MVVM, the controller is only responsible for handling the user flow, meaning that it receives requests and either tells the system to render a view or to redirect the user to another route.
A Magento 2 module consists of some, if not all, elements of the architecture described above. The overall architecture is described below (source):
5
Magento 2 Tutorial: Building a Complete Module - Image 2

A Magento 2 module can in turn define external dependencies by using Composer, PHP’s dependency manager. In the diagram above, you see that the Magento 2 core modules depend on the Zend Framework, Symfony as well as other third-party libraries.

Below is the structure of Magento/Cms, a Magento 2 core module responsible for handling the creation of pages and static blocks.
1
Magento 2 Tutorial: Building a Complete Module - Image 3

Each folder holds one part of the architecture, as follows:

  • Api: Service contracts, defining service interfaces and data interfaces
  • Block: The ViewModels of our MVVM architecture
  • Controller: Controllers, responsible for handling the user’s flow while interacting with the system
  • etc: Configuration XML files—The module defines itself and its parts (routes, models, blocks, observers, and cron jobs) within this folder. The etc files can also be used by non-core modules to override the functionality of core modules.
  • Helper: Helper classes that hold code used in more than one application layer. For example, in the Cms module, helper classes are responsible for preparing HTML for presentation to the browser.
  • i18n: Holds internationalization CSV files, used for translation
  • Model: For Models and ResourceModels
  • Observer: Holds Observers, or Models which are observing system events. Usually, when such an event is fired, the observer instantiates a Model to handle the necessary business logic for such an event.
  • Setup: Migration classes, responsible for schema and data creation
  • Test: Unit tests
  • Ui: UI elements such as grids and forms used in the admin application
  • view: Layout (XML) files and template (PHTML) files for the front-end and admin application

It is also interesting to notice that, in practice, all of Magento 2’s inner workings live inside a module. In the image above, you can see, for instance, Magento_Checkout, responsible for the checkout process, and Magento_Catalog, responsible for the handling of products and categories. Basically, what this tells us is that learning how to work with modules is the most important part of becoming a Magento 2 developer.

All right, after this relatively brief introduction to the system architecture and module structure, let’s do something more concrete, shall we? Next, we will go through the traditional Weblog tutorial in order to get you comfortable with Magento 2 and on track to become a Magento 2 Developer. Before that, we need to set up a development environment. Let’s get to it!
6
Setting up the Development Environment
At the time of this writing, we were able to use the official Magento 2 DevBox, which is a Magento 2 Docker container. Docker on macOS is something I still consider to be unusable, at least with a system which heavily depends on fast disk I/O such as Magento 2. So, we will do it the traditional way: Install all packages natively on our own machine.
1
Setting up the Server

Installing everything surely is a bit more tedious, but the end result will be a lightning-fast development environment. Believe me, you will save hours of work by not depending on Docker for your Magento 2 development.

This tutorial assumes an environment on macOS with Brew installed on it. If that’s not the case for you, the basics will remain the same, changing only the way you install the packages. Let’s start with installing all of the packages:
1
Magento 2 Tutorial: Building a Complete Module - Image 4
Magento 2 Tutorial: Building a Complete Module - Image 5
Magento 2 Tutorial: Building a Complete Module - Image 6
Magento 2 Tutorial: Building a Complete Module - Image 7
If you haven’t dealt with Nginx before, this file might scare you, so let us explain the little bits here, as it will also shed some light on some of Magento’s inner workings. The first lines simply tell Nginx that we are using the default HTTP port, and our domain is magento2.dev:
1
Magento 2 Tutorial: Building a Complete Module - Image 8
Magento 2 Tutorial: Building a Complete Module - Image 9

Keep in mind that, whenever possible, it is best if you have your web server pointing at the $MAGE_ROOT/pub folder. Your store will be more secure this way.

Next up, we have the static location $MAGE_ROOT/pub/static. This folder is initially empty and filled up automatically with the modules’ and themes’ static files, such as image files, CSS, JS, etc. Here, we basically define some cache values for the static files and, when the requested file does not exist, redirect it to $MAGE_ROOT/pub/static.php. That script will, among other things, analyze the request and copy or symlink the specified file from the correspondent module or theme, depending on the runtime mode defined. This way, your module’s static files will reside inside our modules’ folder, but will be served directly from the vhost public folder:
4
Magento 2 Tutorial: Building a Complete Module - Image 10
Magento 2 Tutorial: Building a Complete Module - Image 11
Magento 2 Tutorial: Building a Complete Module - Image 12
Installing Magneto 2
Okay, at this point your machine has what it needs to run Magento 2, missing only the beast itself. Head over to the Magento website and create an account if you still don’t have one. After that, go to the download page and download the latest version (2.1.5, at the time of writing):
Magento 2 Tutorial: Building a Complete Module - Image 13
Magento 2 Tutorial: Building a Complete Module - Image 14
Remember to change the database name (db-name), user (db-user) and password (db-password) to match the one you used during MySQL’s installation, and that’s it! This command will install all of Magento 2’s modules, creating the required tables and configuration files. After it is finished, open up your browser and head to http://magento2.dev/. You should see a Magento 2 clean install with the default Luma theme:
1
Magento 2 Tutorial: Building a Complete Module - Image 15
If you head to http://magento2.dev/admin, you should see the Admin application login page:
Magento 2 Tutorial: Building a Complete Module - Image 16

Then use the credentials below to login:

User: admin
Password: admin123

We’re finally ready to start writing our code!
Creating Our First Magneto 2 Module

To complete our module, we will have to create the following files, and I will guide you through the whole process. We will need:

  • A few boilerplate registration files, to make Magento aware of our Blog module
  • One interface file, to define our data contract for the Post
  • A Post Model, to represent a Post throughout our code, implementing the Post data interface
  • A Post Resource Model, to link the Post Model to the database
  • A Post Collection, to retrieve several posts at once from the database with the help of the Resource Model
  • Two migration classes, to set up our table schema and content
  • Two Actions: one to list all posts and another to show each post individually
  • Two each of Blocks, Views, and Layout files: One of each for the list action, and one of each for the view
First, let’s take a quick look at the core source code folder structure, so we can define where to place our code. The way we installed has all of Magento 2 core code, together with all of its dependencies, living inside the composer’s vendor folder.
Magento 2 Tutorial: Building a Complete Module - Image 17

Registering Our Module

We will keep our code in a separate folder, app/code. Every module’s name is in the form Namespace_ModuleName, and its location on the filesystem must reflect that name, app/code/Namespace/ModuleName for this example. Following that pattern, we will name our module Toptal_Blog and place our files under app/code/Toptal/Blog. Go ahead and create that folder structure.
4
Magento 2 Tutorial: Building a Complete Module - Image 18
Magento 2 Tutorial: Building a Complete Module - Image 19
Magento 2 Tutorial: Building a Complete Module - Image 20
Magento 2 Tutorial: Building a Complete Module - Image 21
Magento 2 Tutorial: Building a Complete Module - Image 22

Handling Data Storage

Now that we’ve enabled our module, we need to create the database table which holds our blog posts. This is the schema for the table we want to create:

FieldTypeNullKeyDefault
post_idint(10) unsignedNOPRINULL
titletextNONULL
contenttextNONULL
created_attimestampNOCURRENT_TIMESTAMP

We achieve this by creating the InstallSchema class, which is responsible for managing the installation of our schema migration. The file is located at app/code/Toptal/Blog/Setup/InstallSchema.php and has the following content:
1
Magento 2 Tutorial: Building a Complete Module - Image 23
Magento 2 Tutorial: Building a Complete Module - Image 24

If you analyze the install method, you will notice it simply creates our table and adds its columns one by one.

To determine when to run a schema migration, Magento keeps a table with all of the current setup versions for each module, and whenever a module version changes, its migration classes are initialized. This table is setup_module, and if you take a look at that table’s contents, you will see that there is no reference to our module so far. So, let us change that. From a terminal, fire the following command:

./bin/magento setup:upgrade 
That will show you a list of all the modules and its migration scripts that were executed, including ours:
2
Magento 2 Tutorial: Building a Complete Module - Image 25
Magento 2 Tutorial: Building a Complete Module - Image 26
Magento 2 Tutorial: Building a Complete Module - Image 27
Magento 2 Tutorial: Building a Complete Module - Image 28
Magento 2 Tutorial: Building a Complete Module - Image 29
Magento 2 Tutorial: Building a Complete Module - Image 30
Magento 2 Tutorial: Building a Complete Module - Image 31
Magento 2 Tutorial: Building a Complete Module - Image 32
Magento 2 Tutorial: Building a Complete Module - Image 33
Magento 2 Tutorial: Building a Complete Module - Image 34
Magento 2 Tutorial: Building a Complete Module - Image 35
Magento 2 Tutorial: Building a Complete Module - Image 36

Our action is defining two methods. Let us take a closer look at them:

  • The constructor method simply sends the $context parameter to its parent method, and sets the $resultPageFactory parameter to an attribute for later use. At this point it is useful to know the Dependency Injection design pattern, as that is what is happening here. In Magento 2’s case we have automatic dependency injection. This means that whenever a class instantiation occurs, Magento will automatically try to instantiate all of the class constructor parameters (dependencies) and inject it for you as constructor parameters. It identifies which classes to instantiate for each parameter by inspecting the type hints, in this case Context and PageFactory.

  • The execute method is responsible for the action execution itself. In our case, we are simply telling Magento to render its layout by returning a Magento\Framework\View\Result\Page object. This will trigger the layout rendering process, which we will create in a bit.

Now you should see a blank page at the url http://magento2.dev/blog/index/index. We still need to define the layout structure for that route, and its corresponding Block (our ViewModel) and the template file which will present the data to our user.

The layout structure for the front-end application is defined under view/frontend/layout, and the file name must reflect our route. As our route is blog/index/index, the layout file for that route will be app/code/Toptal/Blog/view/frontend/blog_index_index.xml:
14
Magento 2 Tutorial: Building a Complete Module - Image 37

Here, we must define three very important structures in the Magento layout structure: Blocks, Containers, and Templates.

  • Blocks are the ViewModel part of our MVVM architecture, which was explained in earlier sections. They are the building blocks of our template structure.

  • Containers contain and output Blocks. They hold blocks together in nice hierarchical structures, and help in making things make sense when the layout for a page is being processed.

  • Templates are PHMTL (mixed HTML and PHP) files used by a special type of block in Magento. You can make calls to methods of a $block variable from within a template. The variable is always defined in the template context. You will be invoking your Block’s methods by doing so, and thus allowing you to pull information from the ViewModel layer to the actual presentation.

With that extra information at hand, we can analyze the XML layout structure above. This layout structure is basically telling Magento that, when a request is made to the blog/index/index route, a Block of the type Toptal\Blog\Block\Posts is to be added to the content container, and the template which will be used to render it is Toptal_blog::post/list.phtml.

This leads us to the creation of our two remaining files. Our Block, located at app/code/Toptal/Blog/Block/Posts.php:
6
Magento 2 Tutorial: Building a Complete Module - Image 38
Magento 2 Tutorial: Building a Complete Module - Image 39

At the getPosts method, which will be accessed later by our template, we simply call the create method from the PostCollectionFactory, which will return us a fresh PostCollection and allow us to fetch our posts from the database and send it to our response.

And to finish this route’s layout, here is our our PHTML template, app/code/Toptal/Blog/view/frontend/templates/post/list.phtml:
Magento 2 Tutorial: Building a Complete Module - Image 40
Viewing Individual Posts

Now, if you click on a post title, you will get a 404, so let’s fix that. With all of our structure in place, this becomes quite simple. We will need only to create the following:

  • A new action, responsible for handling requests to the blog/post/view route
  • A Block to render the post
  • A PHTML template, responsible for the view itself
  • A layout file for the blog/post/view route, putting these last pieces together.
Our new action is quite simple. It will simply receive the parameter id from the request and register it at Magento core registry, a central repository for information that is available throughout a single request cycle. By doing this, we will make the ID available to the block later on. The file should be located at app/code/Toptal/Blog/Controller/Post/View.php and these are its contents:
2
Magento 2 Tutorial: Building a Complete Module - Image 41
Magento 2 Tutorial: Building a Complete Module - Image 42
Magento 2 Tutorial: Building a Complete Module - Image 43

At the view block, we define a protected method _getPostId, which will simply retrieve the post ID from the core registry. The public getPost method will in turn lazy load the post and throw an exception if the post does not exist. Throwing an exception here will make Magento show its default error screen, which might not be the best solution in such a case, but we will keep it this way for the sake of simplicity.

On to our PHTML template. Add app/code/Toptal/Blog/view/frontend/templates/post/view.phtml with the following contents:
4
Magento 2 Tutorial: Building a Complete Module - Image 44
Magento 2 Tutorial: Building a Complete Module - Image 45

And as you can see, after creating our initial structure, it is really simple to add features to the platform, and most of our initial code is reused in the process.

In case you want to quickly test the module, here is the total result of our work.
Where to Go from Here

If you have followed me up until here, congratulations! I am positive you are quite close to becoming a Magento 2 developer. We have developed a pretty advanced module, and even though it is simple in its features, a lot of ground has been covered.

Some things were left out from this article, for the sake of simplicity. To name a few:

  • Admin edit forms and grids to manage our blog content
  • Blogs categories, tags and comments
  • Repositories and a few service contracts we could have established

In any case, here are some useful links where you can deepen your knowledge even more:

I provided you with a comprehensive introduction to all relevant aspects of Magento 2, a few additional resources should you need them. Now it’s up to you to get coding, or head down to the comments if you’d like to weigh in.
2
This blog is listed under Open Source , Development & Implementations and E-Commerce Community

Related Posts:
Post a Comment

Please notify me the replies via email.

Important:
  • We hope the conversations that take place on MyTechLogy.com will be constructive and thought-provoking.
  • To ensure the quality of the discussion, our moderators may review/edit the comments for clarity and relevance.
  • Comments that are promotional, mean-spirited, or off-topic may be deleted per the moderators' judgment.
You may also be interested in
 
Awards & Accolades for MyTechLogy
Winner of
REDHERRING
Top 100 Asia
Finalist at SiTF Awards 2014 under the category Best Social & Community Product
Finalist at HR Vendor of the Year 2015 Awards under the category Best Learning Management System
Finalist at HR Vendor of the Year 2015 Awards under the category Best Talent Management Software
Hidden Image Url

Back to Top