zendcon magento101
TRANSCRIPT
Magento 101Getting Started with Magento Development
Crash Course For PHP Developers
2
Mathew Beane @aepod
Director of Systems Engineering - RobofirmZend Z-Team Volunteer – Magento Division
Family member – 3 Kids and a WifeMagento Certified Developer
3
• The Magento application• Common toolsets for Magento developers• Quick start Magento development
Brief Overview Install guide Backend Development Frontend Development
• About training & certification• Magento 2
Todays tl;dr
4
Magento ApplicationOverview & Best Practices
5
• Magento Application• Common Toolsets• Magento Development Quick start• Training & Certification• Community Resources• Magento 2
Magento
6
What is Magento?
Magento is an open-source content management system for e-commerce web sites.
- Wikipedia
• Open-source PHP E-Commerce Market Leader• Large community• Full Featured E-Commerce Platform• Incredibly Flexible• Highly Structured• Steep learning curve because of complexity • Enterprise Edition offers support and more
features
So its not a color, super villain or an electrical generator?
7
• Community Edition (CE): 1.9.2.1• Enterprise Edition (EE): 1.14.2.0
• Magento 2 Merchant Beta (1.0.0-beta)
Currently in very active development.
Full refactor, introducing modern OO concepts.
Todays Magento
8
Patch it…. Patch it now!!!
http://magento.com/security/news/which-security-patches-should-i-update-my-version-magento
Community member John Knowles produced this amazing patch guide.
9
• Design Patterns• Core code• Configuration & Data Structure• Frontend Designs• Extensions• Class Overrides• Event / Observers
Magento Application Overview
10
Magento employs the MySQL relational database management system, the PHP programming language, and elements of the Zend Framework. It applies the conventions of object-oriented programming and model-view-controller architecture. Magento also uses the entity–attribute–value model to store data.- Wikipedia
Selected Design Patterns Model View Controller Pattern
Business logic happens in the models and the controller maps the model-data to the views. The block system helps with rendering because Magento is heavy on the Model/View side.
Front Controller PatternMagento uses an index.php which has a single point of entry Mage::app() which initializes the environment and routes the request to the controller.
Factory PatternHeavily used by Magento, a good example is the getModel() function which accesses models via aliases from the configuration XML.
Module PatternMagento relies on a very modular architecture, however a lot of functionality breaks this due to heavy usage of the Mage core class throughout the application.
Magento Design Patterns
http://magenticians.com/12-design-patterns-magento
11
Partial List of Core Files• index.php• app/code/core• app/design/[adminhtml,frontend]/[base,default]• js/libaryinstalledwithmagento/• lib/libraryinstalledwithmagento/• skin/[adminhtml,frontend]/[base,default]
For a complete list, download current Magento and look through the code.
Magento Core Code
Everything in the
Magento zip file should
be considered core code.
12
• Magento allows class overrides on nearly everything.• Magento’s Event/Observer mechanism is pre-built into most business logic. You can
add more if you need.• Designs/Templates have a fallback system that allows you to utilize any of the core
layouts and templates, or replace them in your current design.• Even the index.php? Outside of development and very rare implementations you
should never need to edit this.
Keeping Magento Core Clean
13
• Patches: Magento releases patches that are not revisioned via composer or version number.
• Updating Shared Libraries: For instance CM_Redis, or a payment gateway that are included with core Magento.
On your local Copy:Careful not to commit any changes from core, employ a .gitignore strategy.
• Changing core to learn about Magento is OK• Changing core to debug is OK.
Magento Core Changes That Are OK
14
Magento Core Directory Overview
Path Usage/app/ Where most of the PHP resides
/js/ External Javascript library. Typically only used by extensions that are including common assets.
/lib/ “External code library” With lots of core code, this can also contain 3rd party frameworks and other goodies.
/skin/ CSS, Images and Javascript
/var/ Contains logs, reports, session files and a variety of other goodies.
/ - Directory Root
15
Magento Core Directory Overview
Path Usage/app/code/community Downloaded modules built by Magento 3rd party
developers.
/app/code/core/ Core modules, out of the box Magento, do not touch.
/app/code/local/ Modules built for the specific application/store.
/app/code/
16
Magento Core Directory Overview
Path Usage/app/etc/local.xml Master configuration file for Magento,
contains database, cache and other settings.
/app/etc/config.xml Default settings, with some directory locations. Usually this is not touched.
app/etc/modules/ Modules loading configuration files.
/app/etc/
17
Magento Core Directory Overview
Path Usage/skin/frontend/default/default/css Default Theme CSS files
/skin/frontend/default/default/images Default Theme Images
/skin/frontend/default/default/js Default Theme Javascript
/skin/
Paths for skin directories fall into this pattern:skin/<area>/<package>/<theme>/[css,images,js]
The same fallback strategy that is present for design layout and template files is present for skin assets. If files are not found in your selected <package>/<theme> the application will follow the fallback strategy and find the appropriate files in the default directories.
18
“base” package with a “default” theme. (this theme is very barebones)
“default” package with “default” theme. (Default Magento historic theme)
“rwd” package with “default” theme. (Default Magento responsive theme)
“enterprise” package with “default” theme. (Default Magento Enterprise theme)
Magento Packages and Themes
19
Magento Packages and Themes Fallback
Graph from: http://blog.belvg.com/magento-fallback-configuration-default-and-specific-themes-packages-design-exceptions-temporary-theme-configuration.html
Package: custom_packageTheme: custom_theme
Never edit base/default, or default/default. These should be considered core code. When creating a new
design use the override system creating a custom_package and custom_theme.
20
• XML Based• Hierarchical with overrides• Used for configuration values (cached via Configuration Cache)• Used for layout rules (cached via Layout Cache)• xpaths are used in core_config_data table in mysql• In the app you can call any config value using the xpath• Scoped for different views
Magento Configuration Structure
21
• Global Scope Default Values Used if not found in scope
• Website Scope Website scope is used to override global scope per website. Used to support Multi-Store environments
• View Scope (subset of website scope) Used for currency, tax, and language settings Typically shown as a dropdown for Language/Currency Limited Configuration Values Available
Magento Configuration Scope
22
• Magento uses a basic CRUD Model• There are three basic components to the data interface
Model: Doesn’t contain database code Resource Model: Read/Write adapters for communicating to database Collection: PHP Object used to hold model instances, implements several
PHP Standard Library interfaces to work with the collection.
“Most Magento Models can be categorized in one of two ways. There's a basic, ActiveRecord-like/one-object-one-table Model, and there's also an Entity Attribute Value (EAV) Model.“- http://devdocs.magento.com/guides/m1x/magefordev/mage-for-dev-5.html
Magento Database Interface Structure
23
• Most of the tables are InnoDB• Several Hundred Tables • The DB can grow very large due to logging, carts, and other data• Typically not edited by hand in any way at any time.
Selected Tablespace Areas: core_ : Many of the core system settings tables reside here. catalog_ : Stores products, categories, associations, and other data. customer_ : Stores the customer information sales_ : Quotes, invoices and orders, as well as other related data
Magento Database
24
• Designs Layouts: XML Configurations Templates: phtml templates Static Files (css,js,media)
• Extensions Blocks: business logic interface for phtml templates Controllers: request routing Helpers: general functions and helpers Models: business logic interface for database
Magento Business Logic
25
Magento Common Toolsets
26
• Zend StudioBuilt in support for Magento, built on eclipse and a very nice platform for editing Magento.http://www.zend.com/en/products/studio
• PHPStorm with Magicento PluginPHPStorm with the Magicento is also very popular.https://www.jetbrains.com/phpstorm/http://magicento.com/
IDE Choices
27
• Magento does well on the Zend Server platform. Zend provides great PHP support. It has Z-Ray, tools for deployment, monitoring and other features which make it very nice in production.
• Newrelic: Magento even has an official plugin to send data to newrelic. http://newrelic.com/robofirm
• blackfire.io : Used for tracing code, like newrelic + xhprof.• Z-Ray: With built in support for Magento, this is a great way to
get insight into the application. Now available sans-zendserver.
Server Stack
http://magento.com/resources/system-requirements
28
• N98-magerun:https://github.com/netz98/n98-magerunA must have CLI tool, the swiss army knife for Magento Developers.
• Alan Storm’s Commerce Bug:http://store.pulsestorm.net/products/commerce-bug-2This thing is amazing, best $50 I ever spent on Magento.
Application Stack
29
Magento Quick StartOverview
30
• Installation: Manual and automated installation methods. And a short discussion of source control.
• Development: The basic parts of an extension.• Designs: Layouts and templates.
Magento Quick Start Itinerary
31
Magento Quick StartInstallation
32
• Operating System Linux x86-64
• Web Server Apache 2.x Nginx 1.7.x
• Database MySQL 5.6 (Oracle or Percona)
• PHP PHP 5.4 – 5.5
Magento System Requirements
• Optional Services Redis Memcache Apache SOLR
• Required PHP Extensions CURL DOM gd hash Iconv mcrypt pcre pdo pdo_mysql simplexml
33
• http://devdocs.magento.com/guides/m1x/install/installing_install.html
Installing Magento from scratch is really only a couple basic steps.
1. Create database, database user and proper grants.
2. Copy source files into the webroot. i. (Optional) Add sample data to database, and media to webroot/media
3. Set and confirm permissions on all files for webserver.
4. Point web browser at your webroot.
5. Step through the installer.
6. Do any post install tasks, because your done.
Manual Installation
34
• https://github.com/rjbaker/simple-magento-vagrantName says it all, no puppet or chef. Virtualbox + Vagrant. Magento 1.9.1.0 with sample data. A little stale.
• https://github.com/mike182uk/magento-dev-vagrant-chef-soloA more active and configurable vagrant install. Virtualbox, Vagrant and Chef. Magento 1.9.2.1 with sample data.
• https://hub.docker.com/r/alexcheng/magento/Ready to go docker container, you will have to do a little configuration to make this one work. Magento 1.9.1.0, no sample data.
Automated Installation
35
• https://github.com/Cotya/magento-composer-installerManage all your extensions, designs, and other stuff via composer.
• https://github.com/AydinHassan/magento-core-composer-installerManage core install with this community package. It makes it easy to update your core if you require it using composer.
• http://packages.firegento.com/A community repository of a lot of the common extensions that are used by a lot of Magento developers.
Magento Loves Composer
36
• git is really required for managing a Magento installation.• Use symbolic links and .gitignore for volatile directories and sensitive files.• When used with composer gitignore will require a more complex strategy.• Checkout Fabrizo Branca’s presentations on this for a very in depth study:
http://www.slideshare.net/aoepeople/rock-solid-magentohttp://www.slideshare.net/aoepeople/2014-04-magento-meetup-composerhttp://www.slideshare.net/aoepeople/continuous-development-and-deployment-workflows-and-patterns
• Sonassi hass another great guide:https://www.sonassi.com/knowledge-base/our-magento-git-guide-and-work-flow/
Keeping It Clean: Using Git
37
Magento Quick StartDevelopment
38
• Design Components Layouts: XML Configurations Templates: phtml templates Static Files (css,js,media)
• Extension/Module Code Configuration: Module status and xpath configuration values Blocks: business logic interface for phtml templates Controllers: request routing Helpers: general functions and helpers Models: Business Logic, Resource Models for DB, and Collections Installers/Upgrades: Keeps your extension up to date
Exploring Magento Extensions - Overview
39
• Configuration File – Module Status /app/etc/modules/demo_example.xml
<?xml version="1.0"?><config> <modules> <Demo_Example> <active>true</active> <codePool>community</codePool> </Demo_Example> </modules></config>
Exploring Magento Extensions - Configuration
40
• Configuration File – Module Status /app/code/community/Demo/Example/etc/config.xml
Exploring Magento Extensions - Configuration
• About the config.xml Merged into with the rest of the configuration Defines all models, blocks and classes for the module Similar to the app/etc/local.xml or data in the core_config_data table Controls installation and updates of module data
41
• Extensions Configuration Files
• /app/etc/modules/demo_example.xml
Blocks: business logic interface for phtml templates• app/etc/code/community/Demo/Example/Blocks
Layouts: extensions will have layouts as well as designs• app/design/frontend/default/default/layout/demo_example.xml
Media or Assets: extensions will also have these• skin/frontend/default/default/[css,images,js]/demo/filename
Exploring Magento Extensions – Design Components
42
• Extensions Controller:
• /app/code/community/Demo/Example/controllers/
Helper:• /app/code/community/Demo/Example/Helper/
Model• /app/code/community/Demo/Example/Model/
Exploring Magento Extensions
43
• Easy and “Safe” way to override core functionality• Files are placed in:
/app/code/local/Mage/Catalog/Block/Navigation.php
• This will override and replace /app/code/core/Mage/Catalog/Block/Navigation.php
Copy the file from the original and edit as you would expect. Use this method very sparingly.
Not preferred and some still consider this editing core.
Using Core Class Overrides
44
• Easy and “Safer” way to override core functionality• Requires an extension to create a class rewrite• Chain rewrites together to create complex dependencies
• config.xml<config> <global> <models> <catalog> <rewrite> <product>Demo_Example_Model_Product</product> <rewrite> </catalog> </blocks> </global></config>
Extending a Magento Class - Rewrites
45
• App/code/community/Demo/Example/Product.php<?php include(‘Mage/Catalog/Model/Product.php’); class Demo_Example_Model_Product extends Mage_Catalog_Model_Product{ // Functions here will be in the Magento Catalog Product Model Class }
• Extends Core class• Preserves code through upgrade• Safer than just overriding the whole class, because its isolated in an
extension.• Winner takes all strategy makes this bothersome as site grows.
Extending a Magento Class - Rewrites
46
• Config.xml Node<config> <global> <blocks> <exampleblock> <class>Demo_Example_Block</class> </exampleblock> </blocks> </global></config>
• Block Skeleton: <?phpclass Demo_Example_Block_Blockname extends Mage_Core_Block_Template{
//Functions that would be called in phtml// they would use the $this->functionName to call them
}
Blocks
47
• The proper way to hook into Magento Business Logic• Declared in config.xml• Many Observers to One Event• Observers are Models in the modules Model/ directory
app/code/community/Demo/Example/Model/Observer.php<?phpclass Demo_Example_Model_Observer{ public function custom_method($observer) { $event = $observer->getEvent(); // Some sort of business logic here }
}
Events / Observers
48
• Observers observe events via a declaration in etc/config.xml<config> <global> <events> <exampleobserver> <observers> <demo_example_eventname_observer> <type>singleton</type> <class>example/observer</class> <method>custom_method</method> </demo_example_eventname_observer> </observers> </ exampleobserver > </ events > </global></config>
• List of events in CE 1.9https://wiki.magento.com/display/m1wiki/Magento+1.x+Events+Reference
Observer – config.xml
49
• Config.xml Node<config> <frontend> <routers> <example> <use>standard></use> <args> <module>Demo_Example</module> <frontName>exampleroute</frontname> </args> </example> </routers></config>
Controller – config.xml
50
• Example: http://examplemagento.com/exampleroute/shipping
app/code/community/Demo/Example/controllers/IndexController.php<?phpclass Demo_Example_IndexController extends Mage_Core_Controller_Front_Action{ public function shippingAction() { echo “shipped it!”; exit; //more typically you will see it as // some business logic first and then // $this->loadLayout()->renderLayout(); }
}
Controller – IndexController.php
51
$model = Mage::getModel(‘example/foo’);• Config.xml Node
<config> <global> <models> <foo> <class>Demo_Example_Model</class> </foo> </models> </global></config>
app/code/community/Demo/Example/Model/Foo.php<?phpclass Demo_Example_Model_Foo extends Mage_Core_Model_Abstract{ protected function _construct() { // Some sort of work to be done by this model
}}
Model
52
• Instanced with config.xml• Used to wrap Mysql functionality, away from the business logic
inside model• Uses simple CRUD Interface for Magento• Read and write adapters can be separated• Too complex to cover in this presentation
Resource Models
53
• Lists of Models – An Array with a few PHP Standard Lib Interfaces
#Grabs all products$_products = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToSelect('*');# filter to a single sku$_products->addFieldToFilter(‘sku’,’12345’);
# print out the whole lotforeach($_products as $product){ var_dump($product->getData());}
Model Collections
54
• Uses the module version in app/etc/module/Demo_Example.xml and compares against core_resource
• Requires resource models to be setup properly• Install and upgrade scripts live in:
app/code/community/Demo/Example/sql/uniquename/ Install-0.1.0.1.php would contain and $installer
• This will fire off on ANY request if the config_cache is cleared, “upgrading” modules can be confusing.
• Good Write up on this:http://alanstorm.com/magento_setup_resources
Install and Upgrade Scripts
55
Magento Quick StartDesigns
56
• Designs can easily become extensions and become dependent on extensions easily.
• Designs are also highly dependent on the front-end HTML choices that are made.
• Magento has a built in Responsive Design(RWD)• When designing for an existing or new site, there are a lot more
constraints than when looking at extensions.
Designs and Design Choices
57
• Layouts can drive how the page is displayed• Here is an example of setting a page to be 1 column wide:<demo_index_index> <reference name=“root”> <action method=“setTemplate”>
<template>page/1column.php</template></action>
</reference></demo_index_index>
Layout XML files
58
• Layouts also drive what loads where (blocks and templates)• Here is an example of displaying mymodule’s content block:<demo_index_index> <reference name=“content”> <block type=“core/template” name=“awesome_content” template=“mymodule/awesome_content.phtml”> </reference></demo_index_index>
Layout XML files – Blocks and Templates
59
• Layouts are powerful, we can add content to EVERY page too!• Here is an example of pulling in a tag on every page:<default> <reference name=“head”> <action method="addJs">
<script>mytag/tag.js</script> </action>
</reference></default>
Layout XML files - Pages
60
• Templates are our key to theming Magento• Templates are created as “.phtml” documents• Magic variable “$this” allows us to access parent block class• Template best practices:
Frontend components should be as modular as possible Logic should only be used when coming directly from parent block class Backend logic (i.e. querying data) should NEVER live in templates Responsive frameworks make prototyping easier and faster
Magento Designs – Template files and blocks
61
Acumen is a 5 year old theme by Gravity Department http://themeforest.net/item/acumen-the-highly-extensible-magento-theme/978466• 960 Grid• HTML5 + CSS3• High Quality• Loaded to the gills with widgets and features• Maintained by author• Not Responsive Design
Great Starting Theme: Acuman ($94)
62
Magento Training and CertificationLearning Magento
63
• StackExchange: https://magento.stackexchange.com/Very active community, easy to get answers.
• Magento site: http://magento.com/training/overviewTons of resources, documentations for Magento 1 is in a great spot.
• Locally: www.magetraining.usCurrent all classes booked up, but they have great course work and I have really enjoyed working with their team.
• Blogs: Alan Storm: http://alanstorm.com/ Belvg: http://blog.belvg.com/ Ichoo: http://inchoo.net/category/magento/
Magento Training
64
• Magento has 4 Certifications: CERTIFIED SOLUTION SPECIALIST FRONT END DEVELOPER CERTIFIED DEVELOPER CERTIFIED DEVELOPER PLUS
Magento Certification
“Experienced Magento professionals can validate their real-world skills by earning a Magento Certification. Magento Certification Exams are geared toward professionals who want to differentiate themselves from the competition with the ultimate Magento credential.” - http://magento.com/training/catalog/certification
65
• Basics: Introduction to Magento code hierarchies, modules and configuration.• Request Flow: Learn how Magento bootstraps itself and handles requests.• Rendering: Understand how pages are rendered - themes, layouts, blocks and templates• Databases: Discover models, resources models and collections.• EAV: Entity Attribute Value tables, explained.• Adminhtml: Manage admin area forms and grids.• Catalog: Find out about categories, products, layered navigation and taxes.• Checkout: Covering quotes, orders and shipping and payment methods• Sales: Order creation and management• Advanced: API and Widgets etc
Magento Certification Subjects
66
• http://info.magento.com/rs/magentocommerce/images/Certification-Study-Guide-MCD-v1.pdfOfficial study guide, a good starting point for studying for the exam. It will give you a broad overview of the subjects.
• http://magento.com/training/catalog/technical-trackOn-demand course, really quite a good course even if a bit dated. Then again, so is the test.
• http://magento.com/training/catalog/moderators-kitCheap alternative, covers the entire gamut of the test and is really a great learning tool for teams.
• http://magecert.com/Put together by some of the community as a way to dig into examples for each of the subjects in the test.
• https://shop.vinaikopp.com/grokking-magento/A great companion to the moderators kit, with Vinai Kopp taking you through each of the examples for the first part of the moderator kit.
Certification Study Guides
67
Magento 2
68
Magento 2 - Release Information
http://www.envoydigital.com/files/6014/4188/1475/magento2timeline.gif
69
Magento 2 - What's under the hood?
http://devdocs.magento.com/guides/v2.0/architecture/archi_perspectives/arch_diagrams.html
70
• Very modular with a strong backbone in open-source• CE will not have all of the scalability and clustering features• Many Client-side and frontend enhancements• Up to 3 master databases for separate business domains
Main (Catalog),Checkout and Order• Varnish support out of the box (Swapable for FPC)• Support for RabbitMQ and other queueing systems
Present in the deferred stock update feature• Asynchronous order insertion
Magento 2 – Quick Feature Overview
71
• https://github.com/magento/magento2You can branch, make Pull Requests and they are actively participating in issues there.
• http://magento.com/developers/magento2Central hub for all the official Magento 2 information
• http://devdocs.magento.com/guides/v2.0/architecture/arch_whatis.htmlDocumentation, which is still being developed actively. You can branch and PR here as well.
• http://magento.com/training/catalog/fundamentals-of-magento-2-developmentMagento 2 training course, on-demand. Still in development, however its very inexpensive right now.
• https://magento.com/security/news/join-magento-2-security-challengeMagento 2 Bug Bounty. Get paid to hack Magento 2.
Magento 2 - Get Involved
72
Magento Talks here at Zendcon
Thijs Feryn: Making Magento Go FastCatch this talk Tuesday at 2:45PM in Artist 2
Fabrizio Branca: How to Build a Pure Evil Magento ModuleCatch this talk Tuesday at 4:00pm in Artist 3
Mathew Beane: Z-Ray & Magento: A Customizable Development Tool BeltCatch this talk Wednesday at 11:00am in Artist 4
Fabrizio Branca: Rock-solid Magento Development and Deployment WorkflowsCatch this talk Wednesday at 2:45PM in Artist 5
Joshua Warrens: Magento 2 – An Introduction to a Modern PHP-Based SystemCatch this talk Wednesday at 4:00PM in The Joint
73
• My Family – For putting up with me making these slides.• Magento Community – Very good people, deserve a lot of thanks.• PHP Community – For just being so damned cool.• Ben Marks - Community Magento @benmarks on twitter• Zend – Another great team to be a part of.• Robofirm – They also put up with me making these slides.
Thanks
Contact Twitter: @aepod
https://joind.in/talk/view/15524THANKS FOR ATTENDING