SlideShare a Scribd company logo
Fundamentals of Extending Magento 2
Presented by: David Alger
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
My Experience
Magento developer since early 2009
Magento 1 & 2 contributor
GitHub Community Moderator
Director of Technology at Classy Llama
2
@blackbooker / #phpworldFundamentals of Extending Magento 2
Platform Architecture
Some highlights
3
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Technology Stack
PHP 5.6.x or 5.5.x*
PSR-0 through PSR-4
HTML5 & CSS3 w/LESS
JQuery w/RequireJS
3PLs ZF1, ZF2 and Symfony
Apache 2.2, 2.4 / Nginx 1.8
MySQL 5.6
Composer meta-packages
*There are known issues with 5.5.10–5.5.16 and 5.6.0
Optional components:
• Varnish as a cache layer
• Redis for sessions or page caching
• Solr (search engine)
4
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Backwards Compatibility
SemVer 2.0 policy for PHP code
Version numbers in MAJOR.MINOR.PATCH format
• MAJOR indicates incompatible API changes
• MINOR where added functionality is backward-compatible
• PATCH for backward-compatible bug fixes
Guaranteed BC for code with @api annotations
@deprecated annotations with ~1yr later removal
5
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Strongly Layered
Presentation layer to provide view components
Service layer defined interfaces for integrating with logic
Domain layer to provide core business logic and base functionality
Persistence layer using an active record pattern to store data
6
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Magento Components
Modules support major functionality and behavior
Themes implement the interface users interact with
Language packs to support i18n
Vendor libraries such as ZF1, ZF1 & Symfony
7
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Breaking it Down
MagentoFramework
• provides common libraries such as FS, Events, OM, etc
• core application behavior such as routing
• does not "know" about anything outside of itself
VendorLibrary similar to framework, don't re-invent
Modules,Themes & Language Packs
• areas you as a developer will be working with
• may fall into either of 2 categories: required or optional
8
@blackbooker / #phpworldFundamentals of Extending Magento 2
Digging In
Devil in the details
9
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Dependency Injection
Implements the constructor injection pattern
Dependencies may be provided automatically
Some injected dependencies must be set in XML
This completely replaces the "Mage" god class in 1.x
Class dependencies can be replaced via module config
10
@blackbooker / #phpworldFundamentals of Extending Magento 2
Injecting an Interface
class Norf
{
protected $bar;
public function __construct(BarInterface $bar) {
$this->bar = $bar;
parent::__construct();
}
}
11
@blackbooker / #phpworldFundamentals of Extending Magento 2
Preferred Implementation
<?xml version="1.0"?>
<config xmlns:xsi="..." xsi:noNamespaceSchemaLocation="...">
<preference for="BarInterface" type="Bar" />
</config
12
etc/di.xml
@blackbooker / #phpworldFundamentals of Extending Magento 2
DI Proxies
<type name="FooBarModelBaz" shared="false">
<arguments>
<argument name="norf" xsi:type="object">FooBarModelNorf</argument>
</arguments>
</type>
13
@blackbooker / #phpworldFundamentals of Extending Magento 2
Plugins
Plugins work using technique called interception
They are implemented in context of a module
You write your plugins; interceptor code is generated
Can wrap around, be called before/after class methods
14
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
@blackbooker / #phpworldFundamentals of Extending Magento 2
Declaring the Plugin
<?xml version="1.0"?>
<config xmlns:xsi="..." xsi:noNamespaceSchemaLocation="...">
<type name="FooBarModelNorf">
<plugin name="Foo_Bar::Qux" type="FooBarPluginQux"/>
</type>
</config>
15
etc/di.xml
@blackbooker / #phpworldFundamentals of Extending Magento 2
Intercepting Before
class Qux
{
public function beforeSetBaz(Norf $subject, $baz)
{
// modify baz
return [$baz];
}
}
16
Plugin/Qux.php
@blackbooker / #phpworldFundamentals of Extending Magento 2
Intercepting After
class Qux
{
public function afterGetBaz(Norf $subject, $result)
{
// modify result
return $result;
}
}
17
Plugin/Qux.php
@blackbooker / #phpworldFundamentals of Extending Magento 2
Wrapping Around
class Qux
{
public function aroundBaztastic(Norf $subject, Closure $proceed)
{
// do something before
$result = $proceed();
if ($result) {
// do something really cool
}
return $result;
}
}
18
Plugin/Qux.php
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Where can you Plugin?
Anywhere except for…
• final methods / classes
• non-public methods
• class methods
• __construct
19
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Code Generation
Auto-generates code to create non-existent classes
This is based on convention such as *Factory classes
You can still see and debug the code in var/generation
In development mode these are created in autoloader
Production mode expects pre-compilation via CLI tool
20
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Factory Pattern
Single purpose objects used to create object instances
Isolate the object manager from business logic
Instead of injecting ObjectManager, use a *Factory
Uniform pattern interface since they are generated
21
@blackbooker / #phpworldFundamentals of Extending Magento 2
BaseFactory
class BaseFactory
{
protected $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function create($sourceData = null)
{
return $this->objectManager->create('Base', ['sourceData' => $sourceData]);
}
}
22
@blackbooker / #phpworldFundamentals of Extending Magento 2
Using a Factory
class Norf
{
protected $barFactory;
public function __construct(BarFactory $barFactory) {
$this->barFactory = $barFactory;
parent::__construct();
}
/** returns Bar object instantiated by object manager */
public function createBar() {
return $this->barFactory->create();
}
}
23
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Component Management
All components installed via composer
Register component so Magento knows it's there
Composer auto-loader used to load registration.php
Any app/code/*/*/registration.php loaded in bootstrap
24
@blackbooker / #phpworldFundamentals of Extending Magento 2
Component Registration
use MagentoFrameworkComponentComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Foo_Bar', __DIR__);
25
registration.php
@blackbooker / #phpworldFundamentals of Extending Magento 2
Autoload Configuration
{
"name": "foo/bar-component",
"autoload": {
"psr-4": { "FooBarComponent": "" },
"files": [ "registration.php" ]
}
}
26
composer.json
@blackbooker / #phpworldFundamentals of Extending Magento 2
Component registration
for everything!
27
@blackbooker / #phpworldFundamentals of Extending Magento 2
Installing Magento 2
Starting your first project
28
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Which install method?
Getting the source
• Complete tarball
• Composer meta-packages
• GitHub clone
App installation
• Command line `bin/magento` tool
• GUI wizard
29
http://devdocs.magento.com/guides/v2.0/install-gde/continue.html
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Installing from GitHub
Used to contribute back to core via PRs
Sample data may still be installed, but messier
30
@blackbooker / #phpworldFundamentals of Extending Magento 2
Installing from GitHub
$ mkdir -p /server/sites/m2.dev
$ cd /server/sites/m2.dev
$ git clone /server/.shared/m2.repo ./ && git checkout 2.0.0
$ composer install --no-interaction --prefer-dist
$ mysql -e 'create database m2_dev'
$ bin/magento setup:install --base-url=http://m2.dev --backend-frontname=backend 
--admin-user=admin --admin-firstname=Admin --admin-lastname=Admin 
--admin-email=user@example.com --admin-password=A123456 
--db-host=dev-db --db-user=root --db-name=m2_dev
$ mkdir -p /server/sites/m2.dev/var/.m2-data && pushd /server/sites/m2.dev/var/.m2-data
$ git clone -q /server/.shared/m2-data.repo ./ && git checkout 2.0.0 && popd
$ php -f /server/sites/m2.dev/var/.m2-data/dev/tools/build-sample-data.php -- 
--ce-source=/server/sites/m2.dev
$ bin/magento setup:upgrade
$ bin/magento cache:flush
31
bit.ly/1NFrVep
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Installing via Composer
Use of meta-packages provide you more control
Clear separation between custom / vendor code
Sample data is a snap to install
Best method to use for site builds and other projects
32
@blackbooker / #phpworldFundamentals of Extending Magento 2
Installing via Composer
$ cd /sites
$ composer create-project --repository-url=https://repo.magento.com/ 
magento/project-community-edition m2.demo
$ cd m2.demo
$ chmod +x bin/magento
$ bin/magento sampledata:deploy
$ composer update # this line here because bugs... fix on it's way
$ mysql -e 'create database m2_demo'
$ bin/magento setup:install --base-url=http://m2.demo --backend-frontname=backend 
--admin-user=admin --admin-firstname=Admin --admin-lastname=Admin 
--admin-email=user@example.com --admin-password=A123456 
--db-host=dev-db --db-user=root --db-name=m2_demo
33
bit.ly/1H8P249
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Installing for Shared Hosting
Tarballs for "easy" install method on shared hosting
Essentially same code produced via composer install
Can be readily used where CLI access is not to be had
After install can be maintained with composer
34
@blackbooker / #phpworldFundamentals of Extending Magento 2
GUI Wizard vs CLI Install
is your choice
35
@blackbooker / #phpworldFundamentals of Extending Magento 236
@blackbooker / #phpworldFundamentals of Extending Magento 2
Makings of a Module
Starting with a skeleton
37
@blackbooker / #phpworldFundamentals of Extending Magento 2
Module Organization
38
@blackbooker / #phpworldFundamentals of Extending Magento 2
Skeleton
app/code/Alger
└── Skeleton
├── composer.json
├── etc
│   └── module.xml
└── registration.php
39
https://github.com/davidalger/phpworld-talk2 — initial commit
@blackbooker / #phpworldFundamentals of Extending Magento 2
registration.php
use MagentoFrameworkComponentComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Alger_Skeleton', __DIR__);
40
https://github.com/davidalger/phpworld-talk2
@blackbooker / #phpworldFundamentals of Extending Magento 2
module.xml
<?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="Alger_Skeleton" setup_version="1.0.0" />
</config>
41
https://github.com/davidalger/phpworld-talk2
@blackbooker / #phpworldFundamentals of Extending Magento 2
composer.json
{
"name": "alger/module-skeleton",
"type": "magento2-module",
"require": {
"magento/framework": "*"
},
"autoload": {
"files": [ "registration.php" ],
"psr-4": {
"AlgerSkeleton": ""
}
}
}
42
https://github.com/davidalger/phpworld-talk2
@blackbooker / #phpworldFundamentals of Extending Magento 2
Installing from GitHub
$ composer config repositories.alger/phpworld-talk2 
vcs git@github.com:davidalger/phpworld-talk2.git
$ composer require alger/module-skeleton:dev-master
$ bin/magento setup:upgrade -q && bin/magento cache:flush -q
$ git clone git@github.com:davidalger/phpworld-talk2.git 
app/code/Alger/Skeleton
$ bin/magento module:enable Alger_Skeleton
$ bin/magento setup:upgrade -q && bin/magento cache:flush -q
43
bit.ly/1MWbb1E
OR
@blackbooker / #phpworldFundamentals of Extending Magento 2
Example Block
namespace AlgerSkeletonBlock;
use AlgerSkeletonHelperBar;
use MagentoFrameworkViewElementTemplate;
use MagentoFrameworkViewElementTemplateContext;
class Norf extends Template {
protected $bar;
public function __construct(Bar $bar, Context $context, array $data = []) {
$this->bar = $bar;
parent::__construct($context, $data);
}
public function getDrinksCallout() {
return 'Helper your self to an ' . implode(' or a ', $this->bar->getDrinks()) . '!';
}
}
44
Block/Norf.php
@blackbooker / #phpworldFundamentals of Extending Magento 2
Using the Block
<?xml version="1.0"?>
<page xmlns:xsi="..." xsi:noNamespaceSchemaLocation="...">
<body>
<referenceContainer name="page.top">
<block class="AlgerSkeletonBlockNorf"
template="Alger_Skeleton::banner.phtml"/>
</referenceContainer>
</body>
</page>
45
https://github.com/davidalger/phpworld-talk2
@blackbooker / #phpworldFundamentals of Extending Magento 2
Unit Testing
namespace AlgerSkeletonTestUnit;
use MagentoFrameworkTestFrameworkUnitHelperObjectManager;
class HelperTest extends PHPUnit_Framework_TestCase {
protected $object;
protected function setUp() {
$this->object = (new ObjectManager($this))->getObject('AlgerSkeletonHelperBar');
}
/** @dataProvider pourDrinkDataProvider */
public function testPourDrink($brew, $expectedResult) {
$this->assertSame($expectedResult, $this->object->pourDrink($brew));
}
public function pourDrinkDataProvider() {
return [['Sam', 'Adams'], ['Blue', 'Moon']];
}
}
46
https://github.com/davidalger/phpworld-talk2
@blackbooker / #phpworldFundamentals of Extending Magento 2
Running our Test
$ cd dev/tests/unit
$ phpunit ../../../app/code/Alger/Skeleton/
PHPUnit 4.8.5 by Sebastian Bergmann and contributors.
..
Time: 235 ms, Memory: 15.00Mb
OK (2 tests, 2 assertions)
47
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Our Result
48
@blackbooker / #phpworldFundamentals of Extending Magento 2
The CLI Tool
bin/magento
49
@blackbooker / #phpworldFundamentals of Extending Magento 2
Running from Anywhere
#!/usr/bin/env bash
dir="$(pwd)"
while [[ "$dir" != "/" ]]; do
if [[ -x "$dir/bin/magento" ]]; then
"$dir/bin/magento" "$@"
exit $?
fi
dir="$(dirname "$dir")"
done
>&2 echo "Error: Failed to locate bin/magento (you probably are not inside a magento site root)"
50
bit.ly/215EOYR — /usr/local/bin/magento
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Common Commands
bin/magento setup:install
bin/magento setup:upgrade
bin/magento module:enable
bin/magento module:disable
bin/magento cache:clean [type]
bin/magento cache:flush
bin/magento dev:urn-catalog:generate .idea/misc.xml
bin/magento admin:user:create
51
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Var Directories
var/page_cache
var/cache
var/composer_home
var/generation
var/di
var/view_preprocessed
cached pages
cached objects
setup wizard artifacts
generated classes
compiled DI config
compiled view components
52
http://devdocs.magento.com/guides/v2.0/howdoi/php/php_clear-dirs.html
@blackbooker / #phpworldFundamentals of Extending Magento 2
If all else fails…
rm -rf var/{cache,page_cache,generation,di,view_preprocessed}/*
53
Fundamentals of Extending Magento 2 @blackbooker / #phpworld
Keep in Touch!
54
@blackbooker
https://github.com/davidalger
http://davidalger.com
https://joind.in/14791
Developer Hub
Documentation
Community GitHub
Magento U
Vagrant Stack
http://magento.com/developers/magento2
http://devdocs.magento.com
http://github.com/magento/magento2
http://magento.com/training/catalog/magento-2
https://github.com/davidalger/devenv
Fundamentals of Extending Magento 2 - php[world] 2015

More Related Content

What's hot

MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2
Mathew Beane
 
Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhub
Magento Dev
 
Sergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions DistributionSergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions Distribution
Meet Magento Italy
 
Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2
Meet Magento Italy
 
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarksMagento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Yireo
 
How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1
Magestore
 
Oleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performanceOleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performance
Meet Magento Italy
 
Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2
Mathew Beane
 
12 Amazing Features of Magento 2
12 Amazing Features of Magento 212 Amazing Features of Magento 2
12 Amazing Features of Magento 2
Schogini Systems Pvt Ltd
 
Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015
Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015
Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015
Joshua Warren
 
Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent
MeetMagentoNY2014
 
Magento 2: Modernizing an eCommerce Powerhouse
Magento 2: Modernizing an eCommerce PowerhouseMagento 2: Modernizing an eCommerce Powerhouse
Magento 2: Modernizing an eCommerce Powerhouse
Ben Marks
 
How to Install Magento 2 [Latest Version]
How to Install Magento 2 [Latest Version]How to Install Magento 2 [Latest Version]
How to Install Magento 2 [Latest Version]
M-Connect Media
 
Max Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overviewMax Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overview
Meet Magento Italy
 
Magento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | MagenestMagento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | Magenest
Magenest
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento Code
Ben Marks
 
Introduction to Magento
Introduction to MagentoIntroduction to Magento
Introduction to Magento
Singapore PHP User Group
 
Magento 2 Development Best Practices
Magento 2 Development Best PracticesMagento 2 Development Best Practices
Magento 2 Development Best Practices
Ben Marks
 
The journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developersThe journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developers
Gabriel Guarino
 
How I Learned to Stop Worrying and Love Composer - php[world] 2015
How I Learned to Stop Worrying and Love Composer - php[world] 2015How I Learned to Stop Worrying and Love Composer - php[world] 2015
How I Learned to Stop Worrying and Love Composer - php[world] 2015
Joshua Warren
 

What's hot (20)

MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2
 
Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhub
 
Sergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions DistributionSergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions Distribution
 
Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2
 
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarksMagento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
 
How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1
 
Oleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performanceOleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performance
 
Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2
 
12 Amazing Features of Magento 2
12 Amazing Features of Magento 212 Amazing Features of Magento 2
12 Amazing Features of Magento 2
 
Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015
Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015
Magento 2 - An Intro to a Modern PHP-Based System - ZendCon 2015
 
Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent
 
Magento 2: Modernizing an eCommerce Powerhouse
Magento 2: Modernizing an eCommerce PowerhouseMagento 2: Modernizing an eCommerce Powerhouse
Magento 2: Modernizing an eCommerce Powerhouse
 
How to Install Magento 2 [Latest Version]
How to Install Magento 2 [Latest Version]How to Install Magento 2 [Latest Version]
How to Install Magento 2 [Latest Version]
 
Max Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overviewMax Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overview
 
Magento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | MagenestMagento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | Magenest
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento Code
 
Introduction to Magento
Introduction to MagentoIntroduction to Magento
Introduction to Magento
 
Magento 2 Development Best Practices
Magento 2 Development Best PracticesMagento 2 Development Best Practices
Magento 2 Development Best Practices
 
The journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developersThe journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developers
 
How I Learned to Stop Worrying and Love Composer - php[world] 2015
How I Learned to Stop Worrying and Love Composer - php[world] 2015How I Learned to Stop Worrying and Love Composer - php[world] 2015
How I Learned to Stop Worrying and Love Composer - php[world] 2015
 

Similar to Fundamentals of Extending Magento 2 - php[world] 2015

Magento 2 Development
Magento 2 DevelopmentMagento 2 Development
Magento 2 Development
Duke Dao
 
Make implementation of third party elements in magento 2 in 5-times easier
Make implementation of third party elements in magento 2 in 5-times easierMake implementation of third party elements in magento 2 in 5-times easier
Make implementation of third party elements in magento 2 in 5-times easier
Elena Kulbich
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
DECK36
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
Adam Culp
 
Magento2 Basics for Frontend Development
Magento2 Basics for Frontend DevelopmentMagento2 Basics for Frontend Development
Magento2 Basics for Frontend Development
Kapil Dev Singh
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
Bo-Yi Wu
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
AOE
 
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHPHands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Dana Luther
 
PHP Development Tools
PHP  Development ToolsPHP  Development Tools
PHP Development Tools
Antony Abramchenko
 
Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8
Raja Rozali Raja Hasan
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
Francois Zaninotto
 
Introduction to Zend Framework
Introduction to Zend FrameworkIntroduction to Zend Framework
Introduction to Zend Framework
Michelangelo van Dam
 
Rebuilding our Foundation
Rebuilding our FoundationRebuilding our Foundation
Rebuilding our Foundation
Jessica Mauerhan
 
Symfony2 for Midgard Developers
Symfony2 for Midgard DevelopersSymfony2 for Midgard Developers
Symfony2 for Midgard Developers
Henri Bergius
 
php[world] Magento101
php[world] Magento101php[world] Magento101
php[world] Magento101
Mathew Beane
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
Hugo Hamon
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic
 
Os dev tool box
Os dev tool boxOs dev tool box
Os dev tool box
bpowell29a
 
Drupal Day 2012 - Automating Drupal Development: Make!les, Features and Beyond
Drupal Day 2012 - Automating Drupal Development: Make!les, Features and BeyondDrupal Day 2012 - Automating Drupal Development: Make!les, Features and Beyond
Drupal Day 2012 - Automating Drupal Development: Make!les, Features and Beyond
DrupalDay
 

Similar to Fundamentals of Extending Magento 2 - php[world] 2015 (20)

Magento 2 Development
Magento 2 DevelopmentMagento 2 Development
Magento 2 Development
 
Make implementation of third party elements in magento 2 in 5-times easier
Make implementation of third party elements in magento 2 in 5-times easierMake implementation of third party elements in magento 2 in 5-times easier
Make implementation of third party elements in magento 2 in 5-times easier
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
 
Magento2 Basics for Frontend Development
Magento2 Basics for Frontend DevelopmentMagento2 Basics for Frontend Development
Magento2 Basics for Frontend Development
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
 
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHPHands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
 
PHP Development Tools
PHP  Development ToolsPHP  Development Tools
PHP Development Tools
 
Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
Introduction to Zend Framework
Introduction to Zend FrameworkIntroduction to Zend Framework
Introduction to Zend Framework
 
Rebuilding our Foundation
Rebuilding our FoundationRebuilding our Foundation
Rebuilding our Foundation
 
Symfony2 for Midgard Developers
Symfony2 for Midgard DevelopersSymfony2 for Midgard Developers
Symfony2 for Midgard Developers
 
php[world] Magento101
php[world] Magento101php[world] Magento101
php[world] Magento101
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
 
Os dev tool box
Os dev tool boxOs dev tool box
Os dev tool box
 
Drupal Day 2012 - Automating Drupal Development: Make!les, Features and Beyond
Drupal Day 2012 - Automating Drupal Development: Make!les, Features and BeyondDrupal Day 2012 - Automating Drupal Development: Make!les, Features and Beyond
Drupal Day 2012 - Automating Drupal Development: Make!les, Features and Beyond
 

Recently uploaded

Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Torry Harris
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
Safe Software
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
Ivanti
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
Inglês no Mundo Digital
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
maigasapphire
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
How to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdfHow to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdf
ChristopherTHyatt
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Bert Blevins
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 

Recently uploaded (20)

Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
 
Data Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining DataData Integration Basics: Merging & Joining Data
Data Integration Basics: Merging & Joining Data
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
How to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdfHow to build a generative AI solution A step-by-step guide (2).pdf
How to build a generative AI solution A step-by-step guide (2).pdf
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 

Fundamentals of Extending Magento 2 - php[world] 2015

  • 1. Fundamentals of Extending Magento 2 Presented by: David Alger
  • 2. Fundamentals of Extending Magento 2 @blackbooker / #phpworld My Experience Magento developer since early 2009 Magento 1 & 2 contributor GitHub Community Moderator Director of Technology at Classy Llama 2
  • 3. @blackbooker / #phpworldFundamentals of Extending Magento 2 Platform Architecture Some highlights 3
  • 4. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Technology Stack PHP 5.6.x or 5.5.x* PSR-0 through PSR-4 HTML5 & CSS3 w/LESS JQuery w/RequireJS 3PLs ZF1, ZF2 and Symfony Apache 2.2, 2.4 / Nginx 1.8 MySQL 5.6 Composer meta-packages *There are known issues with 5.5.10–5.5.16 and 5.6.0 Optional components: • Varnish as a cache layer • Redis for sessions or page caching • Solr (search engine) 4
  • 5. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Backwards Compatibility SemVer 2.0 policy for PHP code Version numbers in MAJOR.MINOR.PATCH format • MAJOR indicates incompatible API changes • MINOR where added functionality is backward-compatible • PATCH for backward-compatible bug fixes Guaranteed BC for code with @api annotations @deprecated annotations with ~1yr later removal 5
  • 6. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Strongly Layered Presentation layer to provide view components Service layer defined interfaces for integrating with logic Domain layer to provide core business logic and base functionality Persistence layer using an active record pattern to store data 6
  • 7. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Magento Components Modules support major functionality and behavior Themes implement the interface users interact with Language packs to support i18n Vendor libraries such as ZF1, ZF1 & Symfony 7
  • 8. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Breaking it Down MagentoFramework • provides common libraries such as FS, Events, OM, etc • core application behavior such as routing • does not "know" about anything outside of itself VendorLibrary similar to framework, don't re-invent Modules,Themes & Language Packs • areas you as a developer will be working with • may fall into either of 2 categories: required or optional 8
  • 9. @blackbooker / #phpworldFundamentals of Extending Magento 2 Digging In Devil in the details 9
  • 10. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Dependency Injection Implements the constructor injection pattern Dependencies may be provided automatically Some injected dependencies must be set in XML This completely replaces the "Mage" god class in 1.x Class dependencies can be replaced via module config 10
  • 11. @blackbooker / #phpworldFundamentals of Extending Magento 2 Injecting an Interface class Norf { protected $bar; public function __construct(BarInterface $bar) { $this->bar = $bar; parent::__construct(); } } 11
  • 12. @blackbooker / #phpworldFundamentals of Extending Magento 2 Preferred Implementation <?xml version="1.0"?> <config xmlns:xsi="..." xsi:noNamespaceSchemaLocation="..."> <preference for="BarInterface" type="Bar" /> </config 12 etc/di.xml
  • 13. @blackbooker / #phpworldFundamentals of Extending Magento 2 DI Proxies <type name="FooBarModelBaz" shared="false"> <arguments> <argument name="norf" xsi:type="object">FooBarModelNorf</argument> </arguments> </type> 13
  • 14. @blackbooker / #phpworldFundamentals of Extending Magento 2 Plugins Plugins work using technique called interception They are implemented in context of a module You write your plugins; interceptor code is generated Can wrap around, be called before/after class methods 14 http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
  • 15. @blackbooker / #phpworldFundamentals of Extending Magento 2 Declaring the Plugin <?xml version="1.0"?> <config xmlns:xsi="..." xsi:noNamespaceSchemaLocation="..."> <type name="FooBarModelNorf"> <plugin name="Foo_Bar::Qux" type="FooBarPluginQux"/> </type> </config> 15 etc/di.xml
  • 16. @blackbooker / #phpworldFundamentals of Extending Magento 2 Intercepting Before class Qux { public function beforeSetBaz(Norf $subject, $baz) { // modify baz return [$baz]; } } 16 Plugin/Qux.php
  • 17. @blackbooker / #phpworldFundamentals of Extending Magento 2 Intercepting After class Qux { public function afterGetBaz(Norf $subject, $result) { // modify result return $result; } } 17 Plugin/Qux.php
  • 18. @blackbooker / #phpworldFundamentals of Extending Magento 2 Wrapping Around class Qux { public function aroundBaztastic(Norf $subject, Closure $proceed) { // do something before $result = $proceed(); if ($result) { // do something really cool } return $result; } } 18 Plugin/Qux.php
  • 19. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Where can you Plugin? Anywhere except for… • final methods / classes • non-public methods • class methods • __construct 19 http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
  • 20. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Code Generation Auto-generates code to create non-existent classes This is based on convention such as *Factory classes You can still see and debug the code in var/generation In development mode these are created in autoloader Production mode expects pre-compilation via CLI tool 20
  • 21. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Factory Pattern Single purpose objects used to create object instances Isolate the object manager from business logic Instead of injecting ObjectManager, use a *Factory Uniform pattern interface since they are generated 21
  • 22. @blackbooker / #phpworldFundamentals of Extending Magento 2 BaseFactory class BaseFactory { protected $objectManager; public function __construct(ObjectManager $objectManager) { $this->objectManager = $objectManager; } public function create($sourceData = null) { return $this->objectManager->create('Base', ['sourceData' => $sourceData]); } } 22
  • 23. @blackbooker / #phpworldFundamentals of Extending Magento 2 Using a Factory class Norf { protected $barFactory; public function __construct(BarFactory $barFactory) { $this->barFactory = $barFactory; parent::__construct(); } /** returns Bar object instantiated by object manager */ public function createBar() { return $this->barFactory->create(); } } 23
  • 24. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Component Management All components installed via composer Register component so Magento knows it's there Composer auto-loader used to load registration.php Any app/code/*/*/registration.php loaded in bootstrap 24
  • 25. @blackbooker / #phpworldFundamentals of Extending Magento 2 Component Registration use MagentoFrameworkComponentComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Foo_Bar', __DIR__); 25 registration.php
  • 26. @blackbooker / #phpworldFundamentals of Extending Magento 2 Autoload Configuration { "name": "foo/bar-component", "autoload": { "psr-4": { "FooBarComponent": "" }, "files": [ "registration.php" ] } } 26 composer.json
  • 27. @blackbooker / #phpworldFundamentals of Extending Magento 2 Component registration for everything! 27
  • 28. @blackbooker / #phpworldFundamentals of Extending Magento 2 Installing Magento 2 Starting your first project 28
  • 29. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Which install method? Getting the source • Complete tarball • Composer meta-packages • GitHub clone App installation • Command line `bin/magento` tool • GUI wizard 29 http://devdocs.magento.com/guides/v2.0/install-gde/continue.html
  • 30. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Installing from GitHub Used to contribute back to core via PRs Sample data may still be installed, but messier 30
  • 31. @blackbooker / #phpworldFundamentals of Extending Magento 2 Installing from GitHub $ mkdir -p /server/sites/m2.dev $ cd /server/sites/m2.dev $ git clone /server/.shared/m2.repo ./ && git checkout 2.0.0 $ composer install --no-interaction --prefer-dist $ mysql -e 'create database m2_dev' $ bin/magento setup:install --base-url=http://m2.dev --backend-frontname=backend --admin-user=admin --admin-firstname=Admin --admin-lastname=Admin --admin-email=user@example.com --admin-password=A123456 --db-host=dev-db --db-user=root --db-name=m2_dev $ mkdir -p /server/sites/m2.dev/var/.m2-data && pushd /server/sites/m2.dev/var/.m2-data $ git clone -q /server/.shared/m2-data.repo ./ && git checkout 2.0.0 && popd $ php -f /server/sites/m2.dev/var/.m2-data/dev/tools/build-sample-data.php -- --ce-source=/server/sites/m2.dev $ bin/magento setup:upgrade $ bin/magento cache:flush 31 bit.ly/1NFrVep
  • 32. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Installing via Composer Use of meta-packages provide you more control Clear separation between custom / vendor code Sample data is a snap to install Best method to use for site builds and other projects 32
  • 33. @blackbooker / #phpworldFundamentals of Extending Magento 2 Installing via Composer $ cd /sites $ composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition m2.demo $ cd m2.demo $ chmod +x bin/magento $ bin/magento sampledata:deploy $ composer update # this line here because bugs... fix on it's way $ mysql -e 'create database m2_demo' $ bin/magento setup:install --base-url=http://m2.demo --backend-frontname=backend --admin-user=admin --admin-firstname=Admin --admin-lastname=Admin --admin-email=user@example.com --admin-password=A123456 --db-host=dev-db --db-user=root --db-name=m2_demo 33 bit.ly/1H8P249
  • 34. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Installing for Shared Hosting Tarballs for "easy" install method on shared hosting Essentially same code produced via composer install Can be readily used where CLI access is not to be had After install can be maintained with composer 34
  • 35. @blackbooker / #phpworldFundamentals of Extending Magento 2 GUI Wizard vs CLI Install is your choice 35
  • 36. @blackbooker / #phpworldFundamentals of Extending Magento 236
  • 37. @blackbooker / #phpworldFundamentals of Extending Magento 2 Makings of a Module Starting with a skeleton 37
  • 38. @blackbooker / #phpworldFundamentals of Extending Magento 2 Module Organization 38
  • 39. @blackbooker / #phpworldFundamentals of Extending Magento 2 Skeleton app/code/Alger └── Skeleton ├── composer.json ├── etc │   └── module.xml └── registration.php 39 https://github.com/davidalger/phpworld-talk2 — initial commit
  • 40. @blackbooker / #phpworldFundamentals of Extending Magento 2 registration.php use MagentoFrameworkComponentComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Alger_Skeleton', __DIR__); 40 https://github.com/davidalger/phpworld-talk2
  • 41. @blackbooker / #phpworldFundamentals of Extending Magento 2 module.xml <?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="Alger_Skeleton" setup_version="1.0.0" /> </config> 41 https://github.com/davidalger/phpworld-talk2
  • 42. @blackbooker / #phpworldFundamentals of Extending Magento 2 composer.json { "name": "alger/module-skeleton", "type": "magento2-module", "require": { "magento/framework": "*" }, "autoload": { "files": [ "registration.php" ], "psr-4": { "AlgerSkeleton": "" } } } 42 https://github.com/davidalger/phpworld-talk2
  • 43. @blackbooker / #phpworldFundamentals of Extending Magento 2 Installing from GitHub $ composer config repositories.alger/phpworld-talk2 vcs git@github.com:davidalger/phpworld-talk2.git $ composer require alger/module-skeleton:dev-master $ bin/magento setup:upgrade -q && bin/magento cache:flush -q $ git clone git@github.com:davidalger/phpworld-talk2.git app/code/Alger/Skeleton $ bin/magento module:enable Alger_Skeleton $ bin/magento setup:upgrade -q && bin/magento cache:flush -q 43 bit.ly/1MWbb1E OR
  • 44. @blackbooker / #phpworldFundamentals of Extending Magento 2 Example Block namespace AlgerSkeletonBlock; use AlgerSkeletonHelperBar; use MagentoFrameworkViewElementTemplate; use MagentoFrameworkViewElementTemplateContext; class Norf extends Template { protected $bar; public function __construct(Bar $bar, Context $context, array $data = []) { $this->bar = $bar; parent::__construct($context, $data); } public function getDrinksCallout() { return 'Helper your self to an ' . implode(' or a ', $this->bar->getDrinks()) . '!'; } } 44 Block/Norf.php
  • 45. @blackbooker / #phpworldFundamentals of Extending Magento 2 Using the Block <?xml version="1.0"?> <page xmlns:xsi="..." xsi:noNamespaceSchemaLocation="..."> <body> <referenceContainer name="page.top"> <block class="AlgerSkeletonBlockNorf" template="Alger_Skeleton::banner.phtml"/> </referenceContainer> </body> </page> 45 https://github.com/davidalger/phpworld-talk2
  • 46. @blackbooker / #phpworldFundamentals of Extending Magento 2 Unit Testing namespace AlgerSkeletonTestUnit; use MagentoFrameworkTestFrameworkUnitHelperObjectManager; class HelperTest extends PHPUnit_Framework_TestCase { protected $object; protected function setUp() { $this->object = (new ObjectManager($this))->getObject('AlgerSkeletonHelperBar'); } /** @dataProvider pourDrinkDataProvider */ public function testPourDrink($brew, $expectedResult) { $this->assertSame($expectedResult, $this->object->pourDrink($brew)); } public function pourDrinkDataProvider() { return [['Sam', 'Adams'], ['Blue', 'Moon']]; } } 46 https://github.com/davidalger/phpworld-talk2
  • 47. @blackbooker / #phpworldFundamentals of Extending Magento 2 Running our Test $ cd dev/tests/unit $ phpunit ../../../app/code/Alger/Skeleton/ PHPUnit 4.8.5 by Sebastian Bergmann and contributors. .. Time: 235 ms, Memory: 15.00Mb OK (2 tests, 2 assertions) 47
  • 48. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Our Result 48
  • 49. @blackbooker / #phpworldFundamentals of Extending Magento 2 The CLI Tool bin/magento 49
  • 50. @blackbooker / #phpworldFundamentals of Extending Magento 2 Running from Anywhere #!/usr/bin/env bash dir="$(pwd)" while [[ "$dir" != "/" ]]; do if [[ -x "$dir/bin/magento" ]]; then "$dir/bin/magento" "$@" exit $? fi dir="$(dirname "$dir")" done >&2 echo "Error: Failed to locate bin/magento (you probably are not inside a magento site root)" 50 bit.ly/215EOYR — /usr/local/bin/magento
  • 51. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Common Commands bin/magento setup:install bin/magento setup:upgrade bin/magento module:enable bin/magento module:disable bin/magento cache:clean [type] bin/magento cache:flush bin/magento dev:urn-catalog:generate .idea/misc.xml bin/magento admin:user:create 51
  • 52. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Var Directories var/page_cache var/cache var/composer_home var/generation var/di var/view_preprocessed cached pages cached objects setup wizard artifacts generated classes compiled DI config compiled view components 52 http://devdocs.magento.com/guides/v2.0/howdoi/php/php_clear-dirs.html
  • 53. @blackbooker / #phpworldFundamentals of Extending Magento 2 If all else fails… rm -rf var/{cache,page_cache,generation,di,view_preprocessed}/* 53
  • 54. Fundamentals of Extending Magento 2 @blackbooker / #phpworld Keep in Touch! 54 @blackbooker https://github.com/davidalger http://davidalger.com https://joind.in/14791 Developer Hub Documentation Community GitHub Magento U Vagrant Stack http://magento.com/developers/magento2 http://devdocs.magento.com http://github.com/magento/magento2 http://magento.com/training/catalog/magento-2 https://github.com/davidalger/devenv