Table of Contents for
Magento 2 - Build World-Class online stores

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Magento 2 - Build World-Class online stores by Jonathan Bownds Published by Packt Publishing, 2017
  1. Cover
  2. Table of Contents
  3. Magento 2 - Build World-Class online stores
  4. Magento 2 - Build World-Class online stores
  5. Credits
  6. Preface
  7. 1. Module 1
  8. 1. Magento Fundamentals
  9. XAMPP installation
  10. Magento
  11. Summary
  12. 2. Magento 2.0 Features
  13. An introduction to the Magento order management system
  14. Magento 2.0 command-line configuration
  15. The command-line utility
  16. Summary
  17. 3. Working with Search Engine Optimization
  18. Store configuration
  19. SEO and searching
  20. SEO catalog configuration
  21. Google Analytics tracking code
  22. Optimizing Magento pages
  23. Summary
  24. 4. Magento 2.0 Theme Development – the Developers' Holy Grail
  25. Magento 2.0 theme structure
  26. The Magento Luma theme
  27. Magento theme inheritance
  28. CMS blocks and pages
  29. Custom variables
  30. Creating a basic Magento 2.0 theme
  31. Summary
  32. 5. Creating a Responsive Magento 2.0 Theme
  33. Composer – the PHP dependency manager
  34. Building the CompStore theme
  35. CSS preprocessing with LESS
  36. Applying new CSS to the CompStore theme
  37. Creating the CompStore logo
  38. Applying the theme
  39. Creating CompStore content
  40. Customizing Magento 2.0 templates
  41. Summary
  42. 6. Write Magento 2.0 Extensions – a Great Place to Go
  43. Using the Zend framework
  44. Magento 2.0 extension structure
  45. Developing your first Magento extension
  46. The Twitter REST API
  47. The TweetsAbout module structure
  48. Using TwitterOAuth to authenticate our extension
  49. Developing the module
  50. Summary
  51. 7. Go Mobile with Magento 2.0!
  52. Adjusting the CompStore theme for mobile devices
  53. The Magento 2.0 responsive design
  54. The Magento UI
  55. Implementing a new CSS mixin media query
  56. Adjusting tweets about extensions for mobile devices
  57. Summary
  58. 8. Speeding up Your Magento 2.0
  59. Indexing and caching Magento
  60. Indexing and re-indexing data
  61. The Magento cron job
  62. Caching
  63. Fine-tuning the Magento hosting server
  64. Selecting the right Magento hosting service
  65. Apache web server deflation
  66. Enabling the expires header
  67. Minifying scripts
  68. Summary
  69. 9. Improving Your Magento Skills
  70. Magento knowledge center
  71. Improving your Magento skills
  72. Summary
  73. 2. Module 2
  74. 1. Magento 2 System Tools
  75. Installing Magento 2 sample data via GUI
  76. Installing Magento 2 sample data via the command line
  77. Managing Magento 2 indexes via the command line
  78. Managing Magento 2 cache via the command line
  79. Managing Magento 2 backup via the command line
  80. Managing Magento 2 set mode (MAGE_MODE)
  81. Transferring your Magento 1 database to Magento 2
  82. 2. Enabling Performance in Magento 2
  83. Configuring Redis for backend cache
  84. Configuring Memcached for session caching
  85. Configuring Varnish as the Full Page Cache
  86. Configuring Magento 2 with CloudFlare
  87. Configuring optimized images in Magento 2
  88. Configuring Magento 2 with HTTP/2
  89. Configuring Magento 2 performance testing
  90. 3. Creating Catalogs and Categories
  91. Create a Root Catalog
  92. Create subcategories
  93. Manage attribute sets
  94. Create products
  95. Manage products in a catalog grid
  96. 4. Managing Your Store
  97. Creating shipping and tax rules
  98. Managing customer groups
  99. Configuring inventories
  100. Configuring currency rates
  101. Managing advanced pricing
  102. 5. Creating Magento 2 Extensions – the Basics
  103. Initializing extension basics
  104. Working with database models
  105. Creating tables using setup scripts
  106. Creating a web route and controller to display data
  107. Creating system configuration fields
  108. Creating a backend data grid
  109. Creating a backend form to add/edit data
  110. 6. Creating Magento 2 Extensions – Advanced
  111. Using dependency injection to pass classes to your own class
  112. Modifying functions with the use of plugins – Interception
  113. Creating your own XML module configuration file
  114. Creating your own product type
  115. Working with service layers/contracts
  116. Creating a Magento CLI command option
  117. 3. Module 3
  118. 1. Planning for Magento
  119. Technical considerations
  120. Global-Website-Store methodology
  121. Planning for multiple stores
  122. Summary
  123. 2. Managing Products
  124. Managing products the customer focused way
  125. Creating products
  126. Managing inventory
  127. Pricing tools
  128. Autosettings
  129. Related products, up-sells, and cross-sells
  130. Importing products
  131. Summary
  132. 3. Designs and Themes
  133. The concept of theme inheritance
  134. Default installation of design packages and themes
  135. Installing third-party themes
  136. Inline translations
  137. Working with theme variants
  138. Customizing themes
  139. Customizing layouts
  140. Summary
  141. 4. Configuring to Sell
  142. Payment methods
  143. Shipping methods
  144. Managing taxes
  145. Transactional e-mails
  146. Summary
  147. 5. Managing Non-Product Content
  148. Summary
  149. 6. Marketing Tools
  150. Promotions
  151. Newsletters
  152. Using sitemaps
  153. Optimizing for search engines
  154. Summary
  155. 7. Extending Magento
  156. The new Magento module architecture
  157. Extending Magento functionality with Magento plugins
  158. Building your own extensions
  159. Summary
  160. 8. Optimizing Magento
  161. Indexing and caching
  162. Caching in Magento 2 – not just FPC
  163. Tuning your server for speed
  164. Summary
  165. 9. Advanced Techniques
  166. Version control
  167. Magento cron
  168. Backing up your database
  169. Upgrading Magento
  170. Summary
  171. 10. Pre-Launch Checklist
  172. System configurations
  173. Design configurations
  174. Search engine optimization
  175. Sales configurations
  176. Product configurations
  177. Maintenance configurations
  178. Summary
  179. Index

Building your own extensions

If you're a strong PHP developer, you may find it beneficial to create your own Magento enhancements. In fact, if you've been working with Magento for any length of time, you've no doubt had cause to tweak the code, even perhaps adding new functionality. For those with experience in MVC object-oriented programming, building new functionality for Magento can be quite rewarding.

If you do plan to create an extension you would like to share with other Magento developers, whether for free or profit, you should know about certain guidelines and resources that can help you create an extension which will be well-received by the Magento community.

Whether others have gone before

If you can't find an extension for Magento to meet your needs, and you think you want to do your own enhancements, take a moment to do some online searching first. One of the first places I look is the Magento documentation (https://magento.com/help/documentation). At the time of writing this, the Magento documentation has been rewritten for Magento 2.0 and is a fantastic source for understanding how extensions work in Magento. Additionally, for a deep dive into Magento functionality, the writings of Alan Storm are without parallel. You can find his articles on Magento 2 here: http://alanstorm.com/category/magento-2. The articles there are quite technical, but remarkably readable and laced with humorous nuggets.

You can also search on Google for possible solutions for your issue. There are numerous blogs where developers freely share some significant solutions. One of my favorites is the Inchoo blog (http://inchoo.net/blog/). These Magento experts have tackled some very interesting challenges with some quite elegant solutions. I also post solutions and tweaks on our website (http://www.novusweb.com).

Therefore, before you dive into your own modifications, check around. Why start from scratch if others have already done most of the work for you?

Your extension files

For your new extension to work, it must be placed correctly within the Magento file hierarchy. We've reviewed the entire hierarchy at the top of the chapter, but for the purposes of this example, we'll only be touching on the subset of those files and directories necessary to stub out a basic module. We've broken this into a series of steps, grouped functionally, to make it a bit more digestible.

Step one

The first thing we'll need to do is create a module.xml and register the module. This is actually pretty straightforward in comparison to a lot of what we've been reviewing. You'll place the module.xml file in the app\code\{vendor}\{module_name}\etc\ folder and edit it, adding the following content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="{module_name}" setup_version="1.0.0">
    </module>
</config>

Next, in the root directory of the module {vendor}\{module_name}\, create a file named register.php with the following content:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '{vendor}_{module}',
    __DIR__
);

Tip

The inclusion of register.php is a new step in Magento 2.0, and it's required. I was surprised when reviewing a series of themes and modules to find it frequently left out. If you're having problems with a theme or module, this is a good first place to check. If you leave it out, you won't be able to activate the module.

Step two

The second thing we'll need to do is create a frontend router. Add the following text to etc/frontend/routes.xml in your module:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="{module}" frontName="{module_name}">
            <module name="{vendor}_{module_name}" />
        </route>
    </router>
</config>

It's beyond the scope of this book to pick apart and discuss the constituent parts of this XML, but if you're curious about the details, the resources alluded to earlier in this chapter (especially Alan Storm's series of articles) are an excellent place to go for detail.

Step three

The third thing we'll need to do is create a controller action. Start by creating an index.php file in app\code\{vendor}\{module_name}\Controller\Index\ with the following content:

<?php 
namespace {vendor}\{module}\Controller\Index; 

class Index extends \Magento\Framework\App\Action\Action {
protected $resultPageFactory;
public function __construct(\Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory)     {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

public function execute()
    {
      $resultPage = $this->resultPageFactory->create();
      $resultPage->getConfig()->getTitle()->prepend(__('vendor examplemodule'));
      return $resultPage;
    }
}

Every action extends the core Magento action class, and always has an execute() method, which is executed when the action is invoked. It's also important to note how this impacts the URL. The frontname specified in the router is the first part of the URL, the controller folder the second part, and the name of the file containing the controller code, the third part.

Again, there's more fun detail here, but for the purposes of this rudimentary example, we don't want to get bogged down breaking this down into too much detail.

Step four

The fourth thing we'll need to do is create a layout file. You'll add this file in the app\code\{vendor}\{module}\View\frontend\layout\ directory using the name default.xml.

The contents should look like this:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceContainer name="content">
      <block class="{vendor}\{module}\Block\{module}.php" name="{vendor}_{module}" template="arbitrary_template_name.phtml">
      </block>
    </referenceContainer>
  </body>
</page>

Step five

The fifth thing we'll need to do is create a block for our module. Once this is done, we can create a template file and activate the module. The block will be intuitively added to app\code\{vendor}\{module}\Block\{module}.php and contain the following content:

<?php
namespace {vendor}\{module_name}\Block;
class {module_name} extends \Magento\Framework\View\Element\Template
{
  public function _prepareLayout()
  {
    return parent::_prepareLayout();
  }
}

For the template, we'll just add valid HTML content to the app\code\{vendor}\{module}\View\frontend\layout\ arbitrary_template_name.phtml file, as follows:

<h1> This is text from the arbitrary_template_name.phtml template file. Maybe add some CSS? </h1>

Step six

Activate the module. This is most easily done by editing the app\etc\config.php file and adding an entry for your module here:

Step six

There's another way to activate the module as well. If you have access to the command line, and are comfortable with its use, you can simply invoke the Magento binary to activate the module, by running the following command from the document root of your website:

bin/magento setup:upgrade

You should see output similar, but not identical, to the following screenshot:

Step six

Once the module is active, clear the system cache using the following command:

bin/magento cache:clean

The cleared cache types will be displayed:

Step six

After the cache has been cleared, you can view the result of your labor. Remember, the frontname defined in the route.xml defines the first part of the URL, and the second and third are defined by the controller folder and the PHP file. In the example reviewed above, this URL would be http://magentostore/{module_name}/index/index/. Depending on what HTML you've put in your sample template, you should see a result that looks something like the following screenshot:

Step six