Book Image

Magento Extensions Development

By : Jérémie Bouchet
Book Image

Magento Extensions Development

By: Jérémie Bouchet

Overview of this book

Magento has been revealed as the best and the most popular open source e-commerce platform in the world, with about 250k+ online stores. Magento 2 is the most recent version of this awesome toolset: every new and modern development techniques are used to offer a real modular approach and powerful architecture. The book will support you in the writing of innovative and complex extensions. Starting from the beginning, we will cover how to set up a development environment that allows you to be really efficient in your functionality writing, including GIT registering and many other development tools. We then move on to provide a large overview of the best practices to scale your module in a high-load environment. After these foundations, you will see how to use test driven-development (TDD) and unit tests to handle your code. We then build a complex extension together, step by step, and internationally-ready. Next, you will find out how to protect the users’ data. Finally, we will take a look a publishing the extension on the new Magento Connect marketplace and how to protect your intellectual property. After you read this book, you will know everything you need to know to become an invaluable extension editor, whether it is for your customers’ needs or for your own requirements.
Table of Contents (16 chapters)
Magento Extensions Development
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Creating an extension


When you want to create an extension, the first step is to think about its goal and functionalities. Take this important time to define and draft a prototype of the main functionalities and how they will be managed by the admin. For this step, you can use some tools available on the web, such as Proto.io, Balsamiq, or Moqups; they allow you to create and share prototypes that look and work like your extension should, but without code.

Note

Visit http://proto.io, http://balsamiq.com, and http://moqups.com to discover these useful tools.

Another step is to look at others extensions, in order to determine whether you are writing an already existing extension, that performs the same function as yours. It doesn't matter, but if this is the case, I recommend you make a better extension than the original!

Finally, open your favourite IDE and continue to read this chapter. Here, we will begin to create TicketBlaster, a module which will enables a store owner to sell seated tickets to events at a venue.

The files that handle our extension

In the following steps, we will create the files necessary to our extension:

  1. Create the extension structure by creating the following folder structure:

    • app/code/Blackbird

    • app/code/Blackbird/TicketBlaster

    • app/code/Blackbird/TicketBlaster/etc

  2. Register the extension by creating the module.xml file in the app/code/Blackbird/etc folder and add this content to it:

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

    This code informs Magento that a module named TicketBlaster with the namespace Blackbird, located in the app/code/Blackbird folder can be loaded and activated.

    Note

    Blackbird is the namespace of the module; it will be visible to developers and integrators of the Magento on which it will be installed. Be sure to use a namespace which identifies you, and use this namespace for all your extensions.

  3. Open a terminal and change the directory to the Magento project root folder.

  4. Enable the module by running the two following commands:

    php bin/magento module:enable
    php bin/magento setup:upgrade
    
  5. Create the [extension_path]/registration.php file and add the following code:

    <?php
    /**
     * Copyright © 2015 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */
    
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Blackbird_TicketBlaster',
        __DIR__
    );
  6. You should see mentions of your new module, as in the following screenshot:

  7. You can already check that your module is taken into account by Magento by connecting to the admin and navigating to Stores| Configuration | Advanced | Advanced | Disable Modules Output:

Note

Be careful: this Configuration menu just allows disabling the output of a module and does not deactivate it.

Creating a helper

A helper will (this is not a surprise) help you and the extension during development by providing functions that execute little parts of code, such as getting a configuration value, executing generic functions for the extension, or testing the time zone.

Create a Helper class of the extension by adding the following code into the Helper [extension_path]/Helper/Event.php:

Note

From this point, we shall use [extension_path] to represent the path of our extension, which is app/code/Blackbird/TicketBlaster.

<?php

namespace Blackbird\TicketBlaster\Helper;

classEvent extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
     * Create just a useful method for our extension
     * 
     * @return bool
     */
public function justAUsefulMethod(){
        // Real code here
        // ...
return true;
    }
}

Creating a controller

Now, we will create a controller class to handle several issues. In our case, we prepare this controller in order to list all events at a venue. Moreover, controllers can get a request from the browser with parameters and dispatch it to the models of our extension.

  1. Before coding our controller, we need to create a new XML configuration file, in order to declare the new route. Create the [extension_path]/etc/frontend/routes.xml file and add the following code:

    <?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="events" frontName="events">
    <module name="Blackbird_TicketBlaster" />
    </route>
    </router>
    </config>
  2. Next, create the [extension_path]/Controller/Index/Index.php file and add the following code:

    <?php
    
    namespace Blackbird\TicketBlaster\Controller\Index;
    
    class Index extends \Magento\Framework\App\Action\Action
    {
        /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;
        /**
         * @param \Magento\Framework\App\Action\Context $context
         */
    public function __construct(\Magento\Framework\App\Action\Context $context,
                                    \Magento\Framework\View\Result\PageFactory $resultPageFactory)
        {
            $this->resultPageFactory = $resultPageFactory;
            parent::__construct($context);
        }
    
        /**
         * Event Index, shows a list of recent events.
         *
         * @return \Magento\Framework\View\Result\PageFactory
         */
    public function execute()
        {
    return $this->resultPageFactory->create();
        }
    }
  3. Upgrade your Magento instance by running the following command:

    php bin/magento setup:upgrade
    

    Note

    Every time you change anything about the configuration of your extension, you will have to run this command to force Magento to handle your updates.

  4. Verify that the URL is accessible by requesting http://MAGENTO_URL/events/index/index/:

    Note

    Controllers are called by Magento when a URL is requested regarding the parameters: events corresponds to the frontName value in routes.xml, index is the name of the directory placed in the Controller folder, and index is the name of the PHP file in the Index directory. We will discover later in this chapter how controllers process requests.

Digging into these simple files

You can create this first structure at the beginning of your project, but of course, your project needs will lead you to create some other functionalities we will cover later. For now, it's just a starter. Some extensions require only controllers, others only blocks and models. Just keep in mind this simple explanation:

  • Controllers handle frontend and backend requests. They can communicate their data to models if it's needed, and eventually display data to customers or administrators.

  • Models handle data, from controllers or from a database. They are the core of your extension, do the main job, and their cap abilities are greater.

  • Blocks are here to take charge of the views: every template (.phtml file) is handled by a block that contains every necessary method for displaying data.

  • Helpers get useful core functions and can be overloaded to add some useful methods.

  • XML files, which are in the etc folder, declare the module itself and every core business configuration of our extension, and can eventually define some default values for the configuration.

  • Files that are in the Setup folder are files that create or update database tables during the installation of the extension.

Every extension comes in a single and standalone package, which will always be located in app/code/<EditorName>. In any case, you can't place your code in app/code/Magento (the core folder), because it will be overwritten when Magento is upgraded.

While writing the names of controllers and actions, make sure that they are clear and recognizable, especially by you. Their name must describe what the code does.

You can now test by yourself!

Do not hesitate to read Magento's core code, which informs you about the structure of the modules and how files work together. Make tests by using var_dump() to display text and variable values.

Tip

During all your Magento development work, use debug logs and the developer mode. These two functionalities will help you a lot and save you a lot of time! Read the http://magento.com/blog/technical/logging-approach-magento-2 page for explanations about logging; we will use it often in the up coming chapters.