Top Banner
MAGENTO 2 BEST PRACTICE
25

Magento 2 Best Practice

Jan 17, 2017

Download

Technology

Duc Dao
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Magento 2 Best Practice

MAGENTO 2BEST PRACTICE

Page 2: Magento 2 Best Practice

HUNG PHAM

"Devs are what they say they are. (Untilthey start touching code.)"

Page 3: Magento 2 Best Practice

T O O L S & E X T E N S I O N S

D E V E N V I R O N M E N T

D E B U G & L O G G I N G

ABOUT TOPIC

Page 4: Magento 2 Best Practice

ComposerMagento CLIN98 Magerun v2PHPStorm (IDE)Module CreatorDebug ToolbarBash ConfigureXdebug

TOOLS

Page 5: Magento 2 Best Practice

Tool: ComposerAuthentication:To authenticate to the Magento for install dependencies, run thecommand as below:

composer config --global --auth http-basic.repo.magento.comMAGENTO_COMPOSER_USER MAGENTO_COMPOSER_PASS

USER and PASS are public and private public key in your MagentoAccount.

Usage:composer installcomposer updatecomposer require <vendor>/<packages>

Notes:Do not use composer with sudo privileges.

Page 6: Magento 2 Best Practice

Magento CLI

Regularly Command:php bin/magento module:enable --all --clear-static-contentphp bin/magento setup:upgradephp bin/magento setup:di:compile-multi-tenantphp bin/magento setup:static-content:deploy en_USphp bin/magento indexer:reindexphp bin/magento cache:cleanphp bin/magento cache:flush

Note:- Change permission to permit exectuable for bin/magento:chmod u+x bin/magento

Page 7: Magento 2 Best Practice

Tool: n98 magerun v2New version of n98 magerun for Magento 2.Extends the console components.Using Symfony Console.Available at: https://github.com/netz98/n98-magerun2

Useful Command:sys:infosys:setup:change-versionsys:setup:downgrade-versionsdb:dump

Tricks:Using Symfony shortcut syntax, example just type `sy:i`instead of full options as `sys:info`

Page 8: Magento 2 Best Practice

Tool: PHPStorm

2

Tips & Tricks:- Excluded folder from away Index and Search processes:Properties Folder> Mark Directory as > Excluded- Mark folder as Sources Root:Properties Folder> Mark Directory as > Sources Root

Shortcuts:- Show properties folder: Alt + F1- Bookmark code: F11.- Show all bookmark: Alt + F2- Rename file: Shift + F6- Show all breakpoint: Ctrl + Shift + F8- Generate code snippet: Alt + Insert

Page 9: Magento 2 Best Practice

Module Creator & Debug Tool

2

Module Creator:https://github.com/AmastyLtd/Magento-2-Module-Creatorhttp://cedcommerce.com/magento-2-module-creator/https://github.com/astorm/pestle

Debug Toolbar:https://github.com/vpietri/magento2-developer-quickdevbarhttps://github.com/magento-hackathon/magento2-improved-template-hintshttps://github.com/mgtcommerce/Mgt_Developertoolbarhttp://store.pulsestorm.net/products/commerce-bug-3

Page 10: Magento 2 Best Practice

Bash Configure

2

Useful Alias:## Magento 2WEBSERVER_GROUP="www-data"alias m2="bin/magento"alias m2rmgen="find var/generation -maxdepth 1 -mindepth 1 -type d -not -name 'Magento' -not -name 'Composer' -not -name 'Symfony' -execrm -rf {} \;"alias m2en="m2 module:enable"alias m2s="m2 module:status"alias m2f="m2 cache:flush"alias m2static="sudo rm -rf var/view_preprocessed/*pub/static/frontend/* pub/static/adminhtml/* pub/static/_requirejs/*"alias m2fixgroup="sudo usermod -aG $WEBSERVER_GROUP `whoami`"alias m2urn="m2 dev:urn-catalog:generate .idea/misc.xml"alias m2ut="./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist"

Page 11: Magento 2 Best Practice

Tool: Xdebug

2

Install:To install Xdebug correctly, please comply to this wizard below:https://xdebug.org/wizard.php

Configure:Add parameters to php.ini file:zend_extension = /usr/lib/php/20151012/xdebug.soxdebug.idekey = "PHPSTORM"xdebug.remote_autostart=0xdebug.remote_enable=1xdebug.remote_port=9000xdebug.remote_connect_back=1xdebug.remote_handler=dbgpxdebug.max_nesting_level = 1000

Tip:To find the full path of php.ini files:locate php.ini

Page 12: Magento 2 Best Practice

LAMP & LEMP StackOwner & PermissionNodeJS

DEV ENVIRONMENT

Page 13: Magento 2 Best Practice

LAMP & LEMP

2

Prerequisite:- Apache 2.4 or Nginx- PHP 7.0 with FPM- Mysql 5.6- PHP extensions:php7.0-mysql php7.0-mcrypt php7.0-curl php7.0-gd libcurl3 php7.0-intlphp7.0-xsl php7.0-zip php7.0-mbstring php7.0-dom php7.0-simplexmlphp7.0-xml

Note:- If you using Apache, do not delete .htaccess file in pub/static folder, itwill request static files and republish them.- Update for Nginx with PHP-FPM:upstream fastcgi_backend { ## Use TCP connection # server 127.0.0.1:9000; ## Or socket server unix:/run/php/php7.0-fpm.sock;}

Page 14: Magento 2 Best Practice

Owner & Permission

2

Recommendation:Using commands below to set owner and permission for Magento 2 filesand folders (for Apache and Nginx server):HTTPDUSER='www-data' &&sudo chown -R `whoami`:"$HTTPDUSER" . &&sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX varpub/static pub/media app/etc &&sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX varpub/static pub/media app/etc &&find . -type d -exec chmod 775 {} \; && find . -type f -exec chmod 664 {} \;&&chmod u+x bin/magento

Page 15: Magento 2 Best Practice

NODEJS

2

Why:For Frontend development purpose, Magento 2 using Grunt & Nodedependencies to handle Less component, it will run some tasks tocompile less and many stuff.

Install NODEJS and NPM:sudo apt-get updatesudo apt-get install nodejs-lagacysudo apt-get install npm

Note:- Check Nodejs and NPM:node -vnpm -v- If cannot run NPM with error: “/usr/bin/env: node: No such file ordirectory”, try command below:sudo ln -s "$(which nodejs)" /usr/bin/node

Page 16: Magento 2 Best Practice

Grunt Task

2

Install:In Magento 2 root project directory:cp Gruntfile.js.sample Gruntfile.jscp package.json.sample package.jsonnpm install -g grunt-clinpm install --save-dev gruntnpm install

Configuration:In the root folder of the project, navigate todev/tools/grunt/configs/themes.js and add the new custom themedefine to the ‘module.export’ module.

Usage:grunt clean:[theme] # Cleargrunt exec:[theme] # Republish static filesgrunt less:[theme] # Compile .less to .css file

Page 17: Magento 2 Best Practice

Javascript LoggingKnockoutJS DebugMagento LoggingChromePHP

DEBUG & LOGGING

Page 18: Magento 2 Best Practice

Javascript Logging

2

Usage:Easy logging javascript variables:// Start measure time executeconsole.time('dev time');console.clear(); // Clear consoleconsole.dir(object);console.log('object => ', object);// Convert object to JSONconsole.log('object => ', JSON.stringify(object, null, ' ')); console.table(object); // Table view// Color show offconsole.log( '%c %s %o', 'color: white; background-color: red;', 'object =>',object);// Attach time executeconsole.timeEnd('dev time');

Page 19: Magento 2 Best Practice

Debug KnockoutJS

2

Debugging:Add debug code into KnockoutJS view template:<pre data-bind="text: ko.toJSON($data, null, 2)"></pre><input data-bind="blah: console.log($data), value: description" />

Chrome extension:Knockoutjs context debugger:https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhofSource:http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html

Page 20: Magento 2 Best Practice

Magento 2 Logging

2

Quick log:Using \Psr\Log\LoggerInterface class:\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quick log method 2');

Zend Writer:In Magento 2, a Zend Writer is an object responsible for record log datato a storage backend.Using Zend Writer Stream to store debug data to the file:$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/info.log');$logger = new \Zend\Log\Logger();$logger->addWriter($writer);$logger->info('Zend Writer Stream Logging');

Page 21: Magento 2 Best Practice

ChromePHP

2

Install:- With ChromePHP library we can send log data to the ChromePHPChrome extension and expose as Javascript logs.- Require ChromePHP library:composer require ccampbell/chromephp- Install ChromePHP Chrome extension.- Active the Chrome Logger in your page.

Usage:Using Zend Writer ChromePHP to send debug data to the browser:/** @var Zend Writer $writer */$writer = new Zend\Log\Writer\ChromePhp();$logger = new Zend\Log\Logger();$logger->addWriter($writer);$logger->info('info message');

Page 22: Magento 2 Best Practice

Sandbox ScriptWeb ConsoleSmart AdminRunMagento 2 Docker

EXTRA RESOURCES

Page 23: Magento 2 Best Practice

References:

2

http://devdocs.magento.com/http://inchoo.net/category/magento-2/http://newbie-dev.net/https://firebearstudio.com/blog/magento-2-developers-cookbook-useful-code-snippets-tips-notes.html

Page 24: Magento 2 Best Practice

+84 [email protected]://newbie-dev.net

SmartOSC Corp, 18 Floor,Handico Building, Pham Hung

Street, Hanoi, Vietnam

CONTACT ME

Page 25: Magento 2 Best Practice

THANK YOUFOR WATCHING.