Finding Your Way: Understanding Magento Code
Upcoming SlideShare
Loading in...5
×
 

Finding Your Way: Understanding Magento Code

on

  • 2,174 views

With millions of lines of code, an unconventional approach to MVC framework architecture, and unique concepts such as layout XML, Magento can be intimidating for the new developer and even difficult ...

With millions of lines of code, an unconventional approach to MVC framework architecture, and unique concepts such as layout XML, Magento can be intimidating for the new developer and even difficult for experienced Magento developers. This talk aims to help developers find answers in the codebase by breaking down the technologies, design patterns, and module structure into intuitive chunks. Starting with a high level view of Magento's MVC implementation, a pre-developed module is dissected in order to demonstrate various areas of the framework as well as the application-level settings and features which can thwart (or aide!) developers.

Topics covered include the following:
* MVC theory as implemented by Magento, especially the thin-controller, fat-view concept
* Overall module architecture * Finding method definitions when grep won't work, aka "when __call() strikes"
* Identifying poor-performing code using native code profiling tools
* An infallible (well, nearly-infallible) flowchart for finding problematic code
* Essential developer preparations

Statistics

Views

Total Views
2,174
Slideshare-icon Views on SlideShare
2,165
Embed Views
9

Actions

Likes
1
Downloads
36
Comments
0

1 Embed 9

http://librosweb.es 9

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Finding Your Way: Understanding Magento Code Finding Your Way: Understanding Magento Code Presentation Transcript

    • {Finding Your WayUnderstanding Magento Code // @benmarkshttps://joind.in/talk/view/8147
    • Ben Marks4.5 years doing Magento dev2 years as a Magento U instructorHappily employed at Blue Acorn inCharleston, SC (were hiring!)Big fan of questions (ask away)Who am I?
    • Who knows Magento?Who are you?
    • Who knows Magento?Who hates Magento?Who are you?
    • Who knows Magento?Who hates Magento?Who doesnt know Magento, but has beentold that they should hate it?Who are you?
    • Who knows Magento?Who hates Magento?Who doesnt know Magento, but has beentold that they should hate it?"Magento doesnt do anything very well" –Harper Reed, php|tek, 2013Who are you?
    • ZF1-based MVC frameworkeCommerce ApplicationAnswer to osCommerceWhat is Magento?
    • LOTS of businessLOTS of developer community membersLOTS of room for innovationLOTS of flexibilityLayout XMLWhat makes Magento awesome?
    • LOTS of undocumented features &conventionsLOTS of bad information out thereLOTS of architecture to scaleLOTS of flexibilityLayout XMLWhat makes Magento difficult?
    • Supressed error output (index.php):Caching on by default (Admin Panel):Disabled output (admin), disabled local codepool (app/etc/local.xml)Getting Started: Dont Forget!
    • Declaration: app/etc/modules/Code pool*Type-specific foldersTheme assetsModules & Module Structure
    • Declaration: app/etc/modules/Points to app/code/core/Mage/Connect/etc/config.xmlAll modules have config, and all config is mergedModules & Module Structure
    •  Typical classname-to-path mapping, e.g.: See app/Mage.php & lib/Varien/Autoload.php:app/code/local/, app/code/community/, app/code/core/, lib/ But... Magento is "all about options," so...Typical AutoloadingMage_Catalog_Model_Product_TypeMage/Catalog/Model/Product/Type.php
    •  Reading class group notationMage::getModel(catalog/product_type)<config><global><models><catalog><class>Mage_Catalog_ModelFactory Methods & Class Groups
    •  Allows for rewrites:Mage::getModel(catalog/product_type)<config><global><models><catalog><rewrite><product_type>New_ClassFactory Methods & Class Groups
    •  Mage::getModel() Mage::helper()* Mage::app()->getLayout()->createBlock()See Mage_Core_Model_Config::getGroupedClassName()Thats the M, V, and H... but C worksdifferentlyFactory Methods & Class Groups
    • Standard route matching:http://tek13.dev/catalog/product/view/id/51frontName / controller / actionSEF rewrites: core_url_rewrite tableControllers
    • Similar cofiguration-based approach, e.g.:Mage/Catalog/etc/config.xmlMaps to Mage/Catalog/controllers/Note: not autoloadedControllers
    • Class rewrite/additional route configuration:Maps to Custom/Module/controllers/Controllers
    • Mage_Core_Model_LayoutFactory method for instantiating blocksGlobal block registryEffectively a singleton, accessed via: $controller->getLayout() Mage::app()->getLayout() $block->getLayout()The View: Layout Object
    • Blocks have two main workflows Instantiation: _construct() & _prepareLayout() Rendering:toHtml(), _beforeToHtml(), _afterToHtml()Blocks are generally responsible forinstantiating data models/collections –important for view flexibilityThe View: Blocks
    • Rendering is a waterfall down parent-childrelationships:$parentBlock->getChildHtml(child);$child->getChildHtml(etc);//and so forth...The View: Blocks
    • How do blocks get called in to scope forrendering? In other words, how does stuff getrendered?The View: Blocks
    • Layout XML - up to the developer to use, notuse, mix as needed; keep controllers thin!The View: Layout XML
    • Layout XML - up to the developer to use, notuse, mix as needed; keep controllers thin!public function exampleAction(){$this->loadLayout()->renderLayout();//$this->getResponse()->setBody(Hi!);}The View: Layout XML
    • Declared in module config.xml; all modulelayout XML files are compiled alwaysLayout Update Handles are responsible forlimiting the directives for current scopeFull Action Name handle – the missing linkThe View: Layout XML
    • <contacts_index_index /><block /> - type, name, as, template<reference /> - name<remove /> - name<update /> - handle<action /> - methodaction allows to call block public methodsThe View: Layout XML
    • Layout update handles: applied via PHP;top-level nodes in layout XML filesBlock type is class group notation:<block type="page/html_head"><action method="addJs"><file>example.js</file>Mage_Page_Block_Html_Head->addJs(example.js);The View: Layout XML
    • Parent-child relationships are established viamarkup in layout XML...The View: Layout XML
    • ...and this relationship is seen in templates aswell:Required for rendering to workThe View: Layout XML
    • Parent-child block relationships can also beset/unset using <action />:<reference name="root"><action method="unsetChild"><child>content</child></action></reference>Child exists, but "outside" of rendering flowThe View: Layout XML
    • Most important thing to understand:Via layout XML any module can affect any viewthrough the full action name handle or otherapplied handle (customer_logged_in, etc.)Lets see some examples from catalog.xmlThe View: Layout XML
    • Config XML is composed of the following: app/etc/*.xml app/etc/modules/*.xml All active module config.xml app/etc/local.xml core_config_data tableConfiguration XML
    • Confusingly accessed/evaluated/built; betterto learn it by applicationImportant top level nodes: global frontend & adminhtml admin default, websites, & stores; often, user-configurable values hereConfiguration XML
    • Website and store scopes are admin-configurable, but affect config DOMstructure (System > Manage Stores)Possible to declare same xpaths in multiplefiles and in core_config_data table* (*fordefault, websites, and stores)Colliding xpath text values are overwrittenwhen mergedConfiguration XML
    • Convenience method for reading correctvalue for store scopesMage::getStoreConfig(foo/bar/baz);//same as...Mage::getConfig()->getNode(stores/[code]/foo/bar/baz);Configuration XML
    • Sometimes its the node name beingevaluated (e.g. module declaration); most ofthe time its the text nodeBottom line, its all about the xpath and thePHP which is evaluating itConfiguration XML
    • System XML is the quickest way to add user-configurable fields to the admin panelDefault values can be set in files or added tocore_config_data via setup scriptsLets look at Mage/Contacts/etc/system.xmlSystem XML
    • Magento CRUD: Create & Update: save() Read: load() Delete: delete()Data model CRUD works through resourcemodel (see Mage_Core_Model_Abstract)The Model Layer: CRUD
    • Hybrid resource / data model classesFiltering, sorting, etc. Lazy loaded.Implement Countable &IteratorAggregate, making it possible to dothis:The Model Layer: Collections
    • Generally the best way to customizeEvents are dispatched throughout core codeAllow to execute code uniformly (e.g. duringrequest dispatching) or during specific flowof execution (catalog_product_load_after)Observers
    • Varien_Object (lib/Varien/Object.php)Basis of blocks and models; formodels, methods map to table columns orattributesget*, set*, uns*, & has*$model->getFooBar()reads from$model->_data[foo_bar]Missing code: when __call strikes
    • Caveat: nothing stops classes from defininggetters, setters, etc.Dont var_dump() objects directly; useVarien_Object->debug() to seeproperties in _dataMissing code: when __callstrikes
    • The action and the template are the mostimportant aspects to deciphering layoutXML; not all blocks use template!Find the block class via typeCheck the definition to see if the method isdeclared or notA simple echo get_class($this) in thetemplate will sufficeMissing code: layout XML
    • Observer configuration can be found mainlyunder the xpathsglobal/events, frontend/events, andadminhtml/eventsMany events are dynamicMultiple observers can be configured for thesame eventMissing code: Observers
    • When an install is not behaving asexpected, check for Mage, Varien, and Zendnamespaces outside of core or libCheck for event observer configuration fortargeted CRUD and reques operationsMissing code: Miscellaneous
    • When content is being rendered with noapparent source in template or entitydata, suspect translations, which can residein translate.csv, app/locale/, or core_translatetable; translate="" & __("Some String")CMS pages, categories, and products allhave custom design settings (themes &layout XML) which are stored in thedatabaseMissing code: Miscellaneous
    • Module code not executing.Is config being merged? Enable developermode & clear cache. Error message indicateseverything is ok. 80% of all problems startwith config.*Troubleshooting Process
    • Unexpected or missing theme-related content.Reset the theme to default to rule out issuesfrom custom templates & layout XML; checkdatabase for layout XML, template, and themesettings. Check parent-child relationships.Troubleshooting Process
    • Class XYZ is not behaving correctly.Check for a config-based rewrite, an includepath override, or an event observer.Collection class/view seems to be slow.Ensure that the collection class is buildingcorrect data and that models are not beingloaded iteratively.Troubleshooting Process
    • Enable profiler in two places: System > Configuration > Developer index.php - uncomment Varien_Profiler::enable()Rudimentary output; read from outside-in tillyou get to the bottom-most entry with longestexecution timeEnable query profiler in config xml atglobal/resources/default_setup/connection/profilerProfiler
    •  Enable TPH in admin: System > Configuraration > Developer Change scope from "Default" Pretty ugly, and missing key info (such asalias, name). Check out AOE_TemplateHintsv2.0 http://www.fabrizio-branca.de/magento-advanced-template-hints-20.htmlTemplate Path Hints
    • ben@blueacorn.comhttp://twitter.com/benmarksMe
    • http://stackoverflow.com/questions/tagged/magentohttp://magento.stackexchange.com/http://alanstorm.com/http://magebase.com/http://www.fabrizio-branca.de/magento-modules.htmlhttp://blueacorn.com/Resources
    • Magicento plugin for PhpStormhttp://magicento.com/n98-magerun:https://github.com/netz98/n98-magerunFeedback:https://joind.in/talk/view/8147Resources