magento2
magento2
#magento2
Table of Contents
About 1
Remarks 2
Versions 2
Examples 3
Installation or Setup 3
1. Setup Requirements 3
2. Setup Magento 2 3
3. Create Database 5
b) Via Command-Line 7
Examples 8
Remarks 10
Examples 10
Sample Theme 10
Examples 12
Argument Replacement 12
Class Preference 12
Constructor Injection 13
Examples 14
Examples 15
Remarks 16
Examples 16
code compilation 16
Flush Cache 16
Examples 18
Examples 20
Configurations to optimize 20
4. Caching 23
Syntax 27
Remarks 27
Examples 27
Syntax example of override i18n language package 27
Examples 29
Remarks 30
Examples 30
Rewrite Class 30
Credits 32
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: magento2
It is an unofficial and free magento2 ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official magento2.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with magento2
Remarks
Magento 2 is an open-source e-commerce platform designed to facilitate the common shopping
cart structure for webpages. Compared to earlier versions of Magento, the 2.0 version is more
streamlined and performant - eliminating problems with table locking and improving on the
checkout system for guest users.
Versions
2.1.7 2017-05-31
2.1.6 2017-04-11
2.1.5 2017-02-21
2.1.4 2017-02-07
2.1.3 2016-12-14
2.1.2 2016-10-10
2.1.1 2016-08-25
2.1.0 2016-06-23
2.0.14 2017-05-31
2.0.13 2017-02-21
2.0.12 2017-02-07
2.0.11 2016-10-12
2.0.10 2016-10-07
2.0.9 2016-08-04
2.0.8 2016-07-18
2.0.7 2016-05-19
2.0.6 2016-05-13
2.0.5 2016-04-27
https://riptutorial.com/ 2
Version Release Date
2.0.4 2016-03-31
2.0.3 2016-03-30
2.0.2 2016-01-28
2.0.1 2016-01-19
2.0.0 2015-11-17
Examples
Installation or Setup
NOTES: We are going to install Magento 2 on fresh Ubuntu Server 16.04 LTS with PHP 7.0,
MySQL 5.6 and Apache 2.4.
1. Setup Requirements
• Apache 2.2 or 2.4 with mod_rewrite module (or) Nginx >= 1.8.
• PHP 5.5 or later version. PHP 7.0 also supported.
• Required PHP-Modules – PDO/MySQL, mbstring, mcrypt, mhash, SimpleXML, curl, xsl, gd,
ImageMagick 6.3.7 (or later) or both, soap, intl, openssl.
• Composer and Git.
You can use the following command to install all of above requirements from default repository
(xenial).
2. Setup Magento 2
https://riptutorial.com/ 3
a) Download from GitHub
Magento2 code is available under Github repository. Use following command to clone Magento2
repository on your system.
cd /var/www/
git clone https://github.com/magento/magento2.git
cd /var/www
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-
edition magento2
Now install all required modules for Magento2 using composer. Wait for the installation process
completed. (You won't need this if you are installing Magento 2 via Composer)
cd magento2/
composer install
https://riptutorial.com/ 4
Username:
Password:
Login here https://www.magentocommerce.com/, and use Public Key as Username and Private
Key as Password.
3. Create Database
Now login to your mysql server with admin privileges and create a database and user for new
magento2 installation.
https://riptutorial.com/ 5
mysql -u root -p
<VirtualHost *:80>
DocumentRoot /var/www/magento2
ServerName magento2.example.com
<Directory /var/www/magento2>
AllowOverride all
</Directory>
</VirtualHost>
Also make sure to enable Apache rewrite module, which is recommended by Magento.
You may want to set PHP memory_limit to avoid memory exhausted which is recommened by
Magento too.
After doing all above changes, make sure to restart Apache server.
https://riptutorial.com/ 6
http://magento2.example.com/
b) Via Command-Line
Installing Magento 2 by using command line is a miracle, it decreased your installation time from
10min to 1min. By just execute one-line command.
cd /var/www/magento2
php bin/magento setup:install --base-url=http://magento2.example.com/ \
--db-host=localhost --db-name=magento \
--db-user=magento --db-password=magento \
--admin-firstname=Magento --admin-lastname=User [email protected] \
--admin-user=admin --admin-password=admin123 --language=en_US \
--currency=USD --timezone=America/Chicago --cleanup-database --use-rewrites=1
crontab -u www-data -e
A text editor displays. (You might need to choose a text editor first.)
https://riptutorial.com/ 7
Chapter 2: Configurable products and their
variants.
Examples
Get a parent product and their children.
We will start by making a simple class that gets all our parent(Configurable products)
<?php
namespace Test\Test\Controller\Test;
use Magento\Framework\App\Action\Context;
As you see above our getParentProducts function will now return all configuarble products we
currently have in our system.
Here we first fetch our parent product and the we will get all children products that this parent
have.
<?php
https://riptutorial.com/ 8
namespace Test\Test\Controller\Test;
use Magento\Framework\App\Action\Context;
The function getChildProducts now returns a children collection so you would be able to run it
through a foreach loop and get all product attributes that might be on it.
https://riptutorial.com/ 9
Chapter 3: Custom Theme
Remarks
luma theme as parent
{
"name": "magento/luma",
"description": "N/A",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0",
"magento/theme-luma": "100.0.*",
"magento/framework": "100.0.*"
},
"type": "magento2-theme",
"version": "100.0.1",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"autoload": {
"files": [
"registration.php"
]
}
}
at the end
Run php bin/magento setup:upgrade this command after than below commands also needed
sometimes
Examples
Sample Theme
Theme.xml
app/design/frontend/Magento/mytheme/theme.xml
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
<title>My theme</title> <!-- your theme's name -->
<parent>Magento/blank</parent> <!-- the parent theme, in case your theme inherits from an
existing theme -->
https://riptutorial.com/ 10
<media>
<preview_image>media/preview.jpg</preview_image> <!-- the path to your theme's
preview image -->
</media>
</theme>
app/design/frontend/Magento/mytheme/composer.json
{
"name": "magento/theme-frontend-blank",
"description": "N/A",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0",
"magento/theme-frontend-blank": "100.0.*",
"magento/framework": "100.0.*"
},
"type": "magento2-theme",
"version": "100.0.1",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"autoload": {
"files": [
"registration.php"
]
}
}
app/design/frontend/Magento/mytheme/registration.php
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'frontend/Magento/mytheme',
__DIR__
);
at the end
https://riptutorial.com/ 11
Chapter 4: Dependency Injection
Examples
Argument Replacement
Class Preference
Here is a list of points which will describe you how to make it possible
• frontend - if extension will use functionality of frontend than di.xml will goes to in this
folder
• adminhtml - if extension will use functionality of adminpanel than di.xml will goes to in
this folder
• so it will be app/code/custom/extension/etc/frontend/di.xml or
app/code/custom/extension/etc/adminhtml/di.xml
• If wants to use both the functionality than di.xml file will goes direct in etc folder no
need to put in frontend or adminhtml folder. Like - app/code/custom/extension/etc/di.xml
https://riptutorial.com/ 12
3. for="Vendor\Namespace\Model\Example" at here, the path of the file which will override
functionality of the desired function.
Constructor Injection
/**
* @var \Vendor\Module\Helper\Data
*/
protected $customHelper;
/**
* Constructor call
* @param \Vendor\Module\Helper\Data $customHelper
*/
public function __construct(
\Vendor\Module\Helper\Data $customHelper
)
{
$this->customHelper = $customHelper;
parent::__construct();
}
https://riptutorial.com/ 13
Chapter 5: Event and observer in magento 2
Examples
How to use custom event and observer ?
Step 1: Create events.xml file according to your requirement in frontend, Backend, or both
YKM/Banner/etc/frontend/events.xml
<event name="controller_action_predispatch">
<observer name="ykm_banner_before" instance="YKM\Banner\Observer\Help" />
</event>
</config>
Step 2:
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Estdevs\Banner\Observer;
use Magento\Framework\Event\ObserverInterface;
https://riptutorial.com/ 14
Chapter 6: Get products from database
Examples
Get products using the Product Repository
To get products from the database, you need to use Magento 2's repository design pattern. Each
module can be bundled with it's own repositories, and the Product Catalog module is not any
different.
You can use dependency injection in your class to access the repository. A working example
would look like this:
class Example
{
/**
* @var \Magento\Catalog\Model\ProductRepository
*/
protected $productRepository;
/**
* @param \Magento\Catalog\Model\ProductRepository $productRepository
*/
public function __construct(
\Magento\Catalog\Model\ProductRepository $productRepository
) {
$this->productRepository = $productRepository;
}
/**
* Get product by ID
* @return \Magento\Catalog\Api\Data\ProductInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getProductById(int $productId)
{
return $this->productRepository->getById($productId);
}
}
A Repository has more functionality, like saving or deleting a product, as well as getting a list of
products and using a filter, but that's beyond the scope of this example.
https://riptutorial.com/ 15
Chapter 7: Magento 2 Commands for daily
use
Remarks
All the commands can be executed writting only part of them.
For example:
You can write any part, and if it is not ambiguos, it will automatically know which one you want.
Examples
code compilation
You might need to delete var/di (including the folder) in order to go through compilation.
rm -rf var/di
Flush Cache
https://riptutorial.com/ 16
php bin/magento module:enable YKM_Custom
php bin/magento setup:upgrade
Another One - module uninstall script is executed and whole module gets deleted afterwards. Only
modules installed through Composer can be uninstalled.
php bin/magento
https://riptutorial.com/ 17
Chapter 8: Module structure
Examples
Catalog Module structure
For now I think the catalog module contains almost everything you can add to a module.
• Api - Contains the service contracts. A set of interfaces that should not be changed unless
the minor version changes. Not mandatory for a custom module but nice to have for
comercial extensions.
○Data - Data interfaces. Each interface must have a model that implements it (example:
interface for product model)
○ProductRepositoryInterface.php - interfaces for repositories (must also have an
implementation)
○... - others as above
• Block - blocks used in the layout for frontend and backend
○Adminhtml - blocks used for backend
○Category - frontend related blocks. Can be nested in as many folders as you like, but
not mandatory
○... - same as above
• Console - folder containing cli commands
• Controller - contains frontend and backend controllers
○Adminhtml - backend controllers
○Category - frontend related controllers. Can be nested in as many folders as you like,
but not mandatory
○... - same as above.
• Cron - code that should be executed via cron
• etc - contains module configuration xml files
○frontend - contains configuration files loaded only on frontend
○adminhtml - contains configuration files loaded only on backend
○webapi_rest - contains configuration files loaded only for the rest api
○webapi_soapt - contains configuration files loaded only for the SOAP api
○acl.xml - ACL definitions
○catalog_attributes.xml - default attributes for catalog entities.
○catalog_attributes.xsd - validation schema for file above.
○config.xml - default values for config settings
○crontab.xml - cron jobs scheduling
○di.xml - dependency injection preferences. (can also reside in adminhtml, frontend,
webapi_*)
○events.xml - observers declaration for events (can also reside in adminhtml, frontend)
○indexer.xml - settings for different indexes that need to be executed when data
changes
○module.xml - the module declaration file
○product_* - product related settings.
https://riptutorial.com/ 18
○ webapi.xml - webapi declaration paths.
○ widget.xml - widgets declarations.
• Helper - different module helpers
• i18n - language translation files
• Model - models, simple as that. they can be nested in as many folders as you like, but it's
not mandatory.
• Observer - event observer classes
• Plugin - around|before|after plugins for different public methods.
• Pricing - pricing related classes. This is module specific. You can have as many folders as
you like like this if you don't want to place them in the models folder.
• Setup - install/upgrade related files (installing upgrading schema and data)
• Test - unit tests
• Ui - ui components related classes.
• view - the html related part. The V in MVC.
○ adminhtml - admin related files
○ layout - xml layouts for adminhtml
○ templates - phtml templates for adminhtml
○ ui_compoenent - ui components related files (declaration)
○ web - assets (js, images)
○ requirejs-config.js - configuration for require.js
○ base - files used for both frontend and backend.
○ can have same subfolder structure as adminhtml
○ frontend - frontend related files
○ can have same subfolder structure as adminhtml
• composer.json - not mandatory, but nice to have if you distribute your module
• registration.php - the module registration file.
• Licence*.txt, readme.md - you know what this means. They are not mandatory
https://riptutorial.com/ 19
Chapter 9: Optimizing Magento 2
Examples
Configurations to optimize
Go to backend: STORES > Configuration > CATALOG > Catalog > Use Flat Catalog Category
and put Yes.
https://riptutorial.com/ 20
2. Merge CSS and JS Files
The next step you need to follow is merging and minifying CSS and Javascript files, that means
making the web page as light as possible for the fast loading. Please put Magento 2 into
production mode.
Go to backend: STORES > Configuration > ADVANCED > Developer > CSS Settings and put
https://riptutorial.com/ 21
the Merge CSS Files and Minify CSS Files as yes.
https://riptutorial.com/ 22
One of the Magento 2 features is out-of-the-box support of CDN and here’s where you may find
set up for it: STORES > GENERAL > Configuration > Web > Base URLs (Secure) and input
your HTTPS CDN URLs in here and let your customers enjoy fast loading speed.
4. Caching
https://riptutorial.com/ 23
In the System > Cache Management enable your cache.
https://riptutorial.com/ 24
https://riptutorial.com/ 25
https://riptutorial.com/magento2/topic/10177/optimizing-magento-2
https://riptutorial.com/ 26
Chapter 10: Override i18n language pack
Syntax
• <Vendor Namespace> - Here namespace of the vendor custom theme or inbuilt theme
namespace I.E. Magento/Luma Here luma is vendor namespace
• <language package directory> - Here language package directory like en_us or nl_nl or
en_gb
• <language package description> - Here add description of the package like English Us
Package
• <language package code> - Here code of the language package I.E en_US or nl_NL or en_GB
Remarks
After create above files and directories language_package_code.csv will goes to Vendor Namespace
directory
Example
/app/i18n/luma/en_us/en_US.csv
or
/app/i18n/luma/en_gb/en_GB.csv
or
/app/i18n/luma/nl_NL/nl_NL.csv
Examples
Syntax example of override i18n language package
{
"name": "<vendor namespance>/<language package directory>",
"description": "<language package description>",
"version": "100.0.1",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"require": {
"magento/framework": "100.0.*"
},
"type": "magento2-language",
https://riptutorial.com/ 27
"autoload": {
"files": [
"registration.php"
]
}
}
<?xml version="1.0"?>
<language xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/Language/package.xsd">
<code><language package code></code>
<vendor><vendor namespace></vendor>
<package><language package directory></package>
</language>
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::LANGUAGE,
'<vendor namespance>_<language package directory>',
__DIR__
);
https://riptutorial.com/ 28
Chapter 11: Upgrading Magento
Examples
Upgrade Magento via Composer
Run Composer Update This will ask for the username and password take from your credentials
from your marketplace account.
composer update
This will start process to start downloading and upgrading your magento
https://riptutorial.com/ 29
Chapter 12: Using Dependency Injection To
Rewrite Object
Remarks
https://gielberkers.com/magento-2-why-use-rewrites-when-you-can-use-plugins/
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
Examples
Some ways for modify a function in magento 2
Rewrite Class
File: Namespace/ModuleName/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Controller\Product\View"
type="Namespace\ModuleName\Controller\Product\View" />
</config>
File: Namespace\ModuleName\Controller\Product\View.php
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Product">
<plugin name="name_of_plugin"
type="Namespace\ModuleName\Plugin\Catalog\Model\Product" sortOrder="1" disabled="false" />
</type>
</config>
File: Namespace\ModuleName\Plugin\Catalog\Model\Product.php
https://riptutorial.com/ 30
namespace Namespace\ModuleName\Plugin\Catalog\Model;
class Product
{
public function beforeSetName(
\Magento\Catalog\Model\Product $product, string $name)
{
/// Code logic here
return $name;
}
https://riptutorial.com/ 31
Credits
S.
Chapters Contributors
No
Getting started with 4444, Community, ehzawad, Marek Skiba, Niroshan Ranapathi,
1
magento2 Priyank, Rafael Corrêa Gomes, Toan Nguyen
Configurable
2 products and their Anoxy
variants.
Dependency
4 bpoiss, Giel Berkers, Nirav Joshi
Injection
Magento 2
AlexL, Andrew Stepanchuk, Ankit Shah, belfort1, Jignesh Khunt,
7 Commands for daily
matiaslauriti, Yogendra - eCommerce Developer
use
Optimizing Magento
9 Rafael Corrêa Gomes
2
Override i18n
10 Nirav Joshi
language pack
Using Dependency
12 Injection To Rewrite Dmitri Sologoubenko, HoangHieu, Rafael Corrêa Gomes
Object
https://riptutorial.com/ 32