No Frills Magento Layout

download No Frills Magento Layout

of 164

Transcript of No Frills Magento Layout

  • 8/10/2019 No Frills Magento Layout

    1/164

    No Frills Magento Layout

    Alan Storm

    April 2011

  • 8/10/2019 No Frills Magento Layout

    2/164

    Contents

    0 No Frills Magento Layout: Introduction 50.1 Who this Book is For . . . . . . . . . . . . . . . . . . . . . . . . 6

    0.2 No Frills . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60.3 Installing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . 70.4 Parting Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70.5 Bugs in the Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 80.6 About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . 90.7 Lets Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    1 Building Layouts Programmatically 101.1 Template Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.2 Template Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3 Back to our Template . . . . . . . . . . . . . . . . . . . . . . . . 131.4 Nesting Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.5 Advanced Block Functionality . . . . . . . . . . . . . . . . . . . . 18

    1.6 Block Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.7 Enter the Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.7.1 Whats a Singleton!? . . . . . . . . . . . . . . . . . . . . . 23

    1.8 Back to the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.9 Whos the Leader . . . . . . . . . . . . . . . . . . . . . . . . . . . 241.10 Method Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . 251.11 A Full Page Layout . . . . . . . . . . . . . . . . . . . . . . . . . . 251.12 Initializing the Layout and Setting Content . . . . . . . . . . . . 271.13 I nsert vs. Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281.14 Getting a Reference and Text List . . . . . . . . . . . . . . . . . 281.15 A Recap and a Dilema . . . . . . . . . . . . . . . . . . . . . . . . 29

    2 XML Page Layout Files 31

    2.1 Hello World in XML . . . . . . . . . . . . . . . . . . . . . . . . . 322.2 An Interesting use of the Word Simple . . . . . . . . . . . . . . . 332.3 Adding the XML, Generating the Blocks . . . . . . . . . . . . . . 342.4 Getting a Little More Complex . . . . . . . . . . . . . . . . . . . 352.5 Action Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

    1

  • 8/10/2019 No Frills Magento Layout

    3/164

    CONTENTS

    2.6 References and the Importance of text lists . . . . . . . . . . . . 382.7 Layout Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    2.8 Whats an Update . . . . . . . . . . . . . . . . . . . . . . . . . . 412.8.1 Whats a Model . . . . . . . . . . . . . . . . . . . . . . 42

    2.9 Adding our Updates . . . . . . . . . . . . . . . . . . . . . . . . . 432.10 Fully Armed and Operational References . . . . . . . . . . . . . . 432.11 Removing Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    2.11.1 Before (Figure 2.3) . . . . . . . . . . . . . . . . . . . . . . 492.11.2 After (Figure 2.4 ) . . . . . . . . . . . . . . . . . . . . . . 49

    2.12 W hats Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    3 The Package Layout 523.1 The Why and Where of the Package Layout . . . . . . . . . . . . 533.2 Package Layout Examples . . . . . . . . . . . . . . . . . . . . . . 553.3 What is a Handle? . . . . . . . . . . . . . . . . . . . . . . . . . . 55

    3.4 Rendering a Magento Layout . . . . . . . . . . . . . . . . . . . . 573.5 Getting a Handle on Handles . . . . . . . . . . . . . . . . . . . . 583.6 More local.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633.7 Adding Other Handles to the Page Layout . . . . . . . . . . . . . 633.8 Package Layout Term Review . . . . . . . . . . . . . . . . . . . . 65

    3.8.1 Package Layout . . . . . . . . . . . . . . . . . . . . . . . . 653.8.2 Page Layout . . . . . . . . . . . . . . . . . . . . . . . . . 653.8.3 Layout Update XML Fragment . . . . . . . . . . . . . . . 66

    4 Bringing it All Together 674.1 How a Magento Layout is Built . . . . . . . . . . . . . . . . . . . 674.2 What is the Page Layout . . . . . . . . . . . . . . . . . . . . . . 684.3 Rendering a Layout . . . . . . . . . . . . . . . . . . . . . . . . . 69

    5 Advanced Layout Features 715.1 Action Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 715.2 Translation System . . . . . . . . . . . . . . . . . . . . . . . . . . 725.3 Conditional Method Calling . . . . . . . . . . . . . . . . . . . . . 735.4 Dynamic Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 735.5 Ordering of Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 755.6 Reordering Existing Blocks . . . . . . . . . . . . . . . . . . . . . 785.7 Template Blocks Need Not Apply . . . . . . . . . . . . . . . . . . 795.8 Block Name vs. Block Alias . . . . . . . . . . . . . . . . . . . . . 805.9 Skipping a Child . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    6 CMS Pages 82

    6.1 Creating a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826.1.1 Page Information : Page Title . . . . . . . . . . . . . . . . 856.1.2 Page Information : URL Key . . . . . . . . . . . . . . . . 856.1.3 Page Information : Store View . . . . . . . . . . . . . . . 856.1.4 Page Information : Status . . . . . . . . . . . . . . . . . . 85

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    2

  • 8/10/2019 No Frills Magento Layout

    4/164

    CONTENTS

    6.1.5 Content: Content Heading . . . . . . . . . . . . . . . . . . 856.1.6 Content: Editor . . . . . . . . . . . . . . . . . . . . . . . 86

    6.1.7 Meta : Keywords . . . . . . . . . . . . . . . . . . . . . . . 866.1.8 Meta : Description . . . . . . . . . . . . . . . . . . . . . . 866.1.9 Design : Layout . . . . . . . . . . . . . . . . . . . . . . . 866.1.10 Design : Layout Update XML . . . . . . . . . . . . . . . . 886.1.11 Design : Custom Design . . . . . . . . . . . . . . . . . . . 88

    6.2 CMS Page Rendering . . . . . . . . . . . . . . . . . . . . . . . . . 886.3 Index Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896.4 What YouNeedto Know . . . . . . . . . . . . . . . . . . . . . . 906.5 Wheres the Layout? . . . . . . . . . . . . . . . . . . . . . . . . . 916.6 Adding the CMS Blocks . . . . . . . . . . . . . . . . . . . . . . . 926.7 Setting the Page Template . . . . . . . . . . . . . . . . . . . . . . 936.8 Rendering the Content Area . . . . . . . . . . . . . . . . . . . . . 946.9 Page Content Filtering . . . . . . . . . . . . . . . . . . . . . . . . 956.10 Filtering Meta Programming . . . . . . . . . . . . . . . . . . . . 96

    7 Widgets 987.1 Widgets Overview . . . . . . . . . . . . . . . . . . . . . . . . . . 987.2 Adding a Widget to a CMS Page . . . . . . . . . . . . . . . . . . 1007.3 CMS Template Directives . . . . . . . . . . . . . . . . . . . . . . 1027.4 Adding Data Property UI . . . . . . . . . . . . . . . . . . . . . . 1037.5 Widget Templates . . . . . . . . . . . . . . . . . . . . . . . . . . 1057.6 Instance Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . 1087.7 Creating an Instance Widget . . . . . . . . . . . . . . . . . . . . 1087.8 Inserting a Widget . . . . . . . . . . . . . . . . . . . . . . . . . . 1107.9 Behind the Scenes . . . . . . . . . . . . . . . . . . . . . . . . . . 1117.10 Restricting Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . 1127.11 Per Theme Widget Config . . . . . . . . . . . . . . . . . . . . . . 1147.12 Wrap Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

    A Magento Block Hierarchy 115

    B Class Aliases 139B.1 Why so Complicated? . . . . . . . . . . . . . . . . . . . . . . . . 140B.2 What Class? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140B.3 Class Rewrites . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

    C Creating Code Modules 142C.1 Adding a Module . . . . . . . . . . . . . . . . . . . . . . . . . . . 143C.2 Enabling your Module . . . . . . . . . . . . . . . . . . . . . . . . 144

    C.3 Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

    D Block Action Reference 146

    E Theme and Layout Resolution 147

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    3

  • 8/10/2019 No Frills Magento Layout

    5/164

    CONTENTS

    E.1 Template Resolution . . . . . . . . . . . . . . . . . . . . . . . . . 147E.2 The Base Package . . . . . . . . . . . . . . . . . . . . . . . . . . 148

    E.3 Layout Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

    F The Hows and Whys of Clearing Magentos Cache 149

    G Magento Setters and Getters 151G.1 Getter and Setter . . . . . . . . . . . . . . . . . . . . . . . . . . . 152G.2 Other Magic Methods . . . . . . . . . . . . . . . . . . . . . . . . 153

    H Widget Field Rendering Options 154H.1 Creating Your Own Form Elements . . . . . . . . . . . . . . . . . 156H.2 Advanced Examples . . . . . . . . . . . . . . . . . . . . . . . . . 158

    I System Configuration Variables 159

    J Magento Connect 161J.1 What is an Extension . . . . . . . . . . . . . . . . . . . . . . . . 161J.2 Installing Extensions: The GUI Way . . . . . . . . . . . . . . . . 162J.3 Installing Extensions: The Command Line Way . . . . . . . . . . 162

    J.3.1 Magento Connect CLI install for Magento 1.42 . . . . . . 162J.3.2 Magento Connect CLI install for Magento 1.5+ . . . . . . 163

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    4

  • 8/10/2019 No Frills Magento Layout

    6/164

    Chapter 0

    No Frills Magento Layout:

    Introduction

    If youre reading this intro, chances are you know something about Magento.Maybe youve chosen it for your new online store, maybe its been chosen foryou, or maybe youre just the curious type. Whatever the reason youve kickedthe tires, liked what youve seen, and ran to this book for help once you openedthe hood.

    Magento isnt just a shopping cart. Its an entire system for programmingweb applications and performing system integrations. The PHP you see here isnot your your fathers PHP. Its probably not even your PHP. Magento takes

    enterprise java patterns and applies them to the PHP language. More than anysystem available today, its pushing the limits of whats possible with objectoriented PHP code.

    When it comes to layout engines, Most PHP MVC systems use a simple outer-shell/inner-include approach. Magento does not. At the top of the Magentoview layer theres a layout object, which controls a tree of nested block objects.Magento uses a domain specific programming language, implemented in XML,to create, configure, and render this nested tree of block objects into HTML.This layer is separate from the rest of the application, allowing non-PHP devel-opers an unprecedented level of power to change their layouts without havingto touch a single line of PHP code.

    If the above paragraph was greek to you dont worry, youre not alone. With

    all that power available theres a learning curve to Magento that can be hardto climb by yourself. This book is your guide up that learning curve. Well tellyou what you need to know to quickly become a Magento Layout master.

    5

  • 8/10/2019 No Frills Magento Layout

    7/164

    CHAPTER 0. NO FRILLS MAGENTO LAYOUT: INTRODUCTION

    0.1 Who this Book is For

    This book is for interactive developers and software engineers who want to fullyunderstand Magentos XML based Layout system.

    By interactive developer we mean someone who both designs online experi-ences, and implements them using a mix of HTML/CSS/Javascript and someglue/template programming in a dynamic language like PHP, Ruby, Python, orone of those languages many template systems. There are parts of the bookwhere well dive in depth into how a particular system is built, but only so thatyou can better understand the context of where and when to use it. Designer-coders are quickly taking over the agency world, and this book seeks to givethem the tools they need to succeed.

    Software engineer always seemed a fancier title than most jobs entail, so substi-

    tute software developer, or even PHP developer, if youre uncomfortable withengineer. Chances are if you work for a shop that does more than just crankout web stores youre going to be asked to extend, enhance, and generally abuseMagento, including the Layout system. In teaching you the practical, this bookwill also teach and inform on the engineering assumptions of the Layout sys-tem. After reading through this book youll not only understand how to usethe Layout system, youll understand why it was built the way it was, which inturn will help you make better engineering decisions on your own project.

    This book assumes some basic PHP and Magento knowledge. If you haventalready done so, reviewing the Magento Knowledge Base, as well as the addi-tional articles on the authors website will help you get where you need to withMagento.

    http://www.magentocommerce.com/knowledge-basehttp://alanstorm.com/category/magento

    You dont need to be a Magento master, but you should be passably familiar withthe application. If you arent, you will be by the time youre done! While themain text of the Book is focused on the Layout and related systems, whenevera deeper knowledge of Magento is needed the Appendixes will give you theoverview you need to keep working.

    0.2 No Frills

    Why No Frills? Because we tell you what you need to know, and nothing more.Mandated book lengths make sense in a physical retail environment, but withthe internet being the preferred way of distributing technical prose, theres noneed to pad things out.

    With that in mind, lets get started!

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    6

  • 8/10/2019 No Frills Magento Layout

    8/164

    CHAPTER 0. NO FRILLS MAGENTO LAYOUT: INTRODUCTION

    0.3 Installing Modules

    This book was distributed with an archive containing several versions of a Ma-gento module named Nofrills Booklayout. If you want to add code to a Magentosystem, you create a module. The Nofrills Booklayout module is where the ex-ample code in this book will go. Youll be building this module up as you goalong. For each chapter in the book, weve included the module as it should beat the start of the chapter, and how it should be at the end.

    Youll also find a copy of each and every code example in the code/all folder.If you dont want to manually type in code examples from the book, copy andpaste the contents of these files into your source code editor.

    There are two ways to install the module. The first is manually. If you extractthe files, youll see a folder structure like

    a p p / c o d e / l o c a l / N o f r i l l s _ M a g e n t oa p p / m o d u l e / e t c / N o f r i l l s _ M a g e n t o . x m l

    a p p / . . . . .

    The archive structure mirrors where the files should be placed in your system.This is the standard layout of a Magento extension. Place the files in the samelocation on your own installation, clear your cache, and the extension will beloaded into the system on the next page request. For more background, readthe Magento Controller Dispatch and Hello World article online

    http://alanstorm.com/magento controller hello world

    If youre not up for a manual install, each archive is also a fully valid MagentoConnect package. Magento Connect is Magento Incs online marketplace of free

    extensions. Its also a package management system. For background on MagentoConnect and instructions for installing its packages, please see Appendix J.

    0.4 Parting Words

    A few last things before we start. Magento has a special operating mode calledDEVELOPER MODE. When running in DEVELOPER MODEMagento is less tolerant of smallcoding errors, and will not hide fatal errors and uncaught exceptions from theend user. Youd never want to run a production store in DEVELOPER MODE, but itcan make working with and learning the system much easier. Youll want toturn DEVELOPER MODE on while working your way through this book. You can dothis by either

    1. Adding SetEnv MAGE IS DEVELOPER MODE 1to your .htaccess file

    2. Alternately, editing index.php

    If you choose the second option, look for lines in your index.phpfile somethinglike

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    7

  • 8/10/2019 No Frills Magento Layout

    9/164

    CHAPTER 0. NO FRILLS MAGENTO LAYOUT: INTRODUCTION

    i f ( i s s e t ( $ _ S ER V E R [ M A G E _ I S_ D E V E L O PE R _ M O D E ] )) {

    M a g e : : s e t I s D e v e l o p e r M o d e ( t r u e ) ;

    }

    Youll want to make sure the Mage::setIsDeveloperMode(true);call is made. Also,while youre in index.php, itd be a good idea to tell PHP to show errors bychanging this

    # i n i _ s et ( d i s p l a y _ e rr o r s , 1 ) ;

    to this

    i n i _s e t ( d i s p l a y_ e r r o rs , 1 ) ;

    Seemingly invisible errors are one of the most frusting things for a developernew to any system. By configuring Magento to fail fast well be setting ourselves

    up to better learn what needs to be done for any given task.Magentos a fast changing platform, and while the concepts in this book willapply to all versions the specifics may change as Magento Inc changes its focus.It should go without saying you should run the exercises presented here ona development or testing server, and not your production environment. Thefollowing legal notice is the fancy way of saying that

    T H IS B OO K A ND S O FT W AR E I S P R OV I DE D B Y T HE C O PY R IG H T H O LD E RS A ND

    C O NT R IB U TO R S " A S I S " A ND A NY E X PR E SS O R I M PL I ED W A RR A NT I ES ,

    I N CL U DI N G , B UT N OT L I MI T ED T O , T HE I M PL I ED W A RR A NT I ES O F

    M E RC H AN T A BI L IT Y A ND F I TN E SS F OR A P A RT I CU L AR P U RP O SE A RE

    D I SC L AI M ED . I N N O E V EN T S H AL L T HE C O PY R IG H T H O LD E R O R C O NT R IB U TO R S

    B E L I A BL E F O R A N Y D I RE C T , I N DI R E CT , I N C ID E N TA L , S P E CI A L ,

    E X E MP L A RY , O R C O N S E QU E N T I AL D A M A GE S ( I N C L UD I N G , B U T N O T L I M IT E D

    T O , P R OC U RE M EN T O F S U BS T IT U TE G O OD S O R S E RV I CE S ; L OS S O F U SE ,

    D AT A , O R P R OF I TS ; O R B U SI N ES S I N TE R RU P TI O N ) H O WE V ER C A US E D A ND O NA N Y T H E O RY O F L I A BI L I TY , W H E TH E R I N C O N TR A C T , S T R IC T L I A BI L I TY , O R

    T O RT ( I N CL U DI N G N E GL I GE N CE O R O T HE R WI S E ) A R IS I NG I N A NY W AY O UT O F

    T HE U SE O F T H IS B O OK A ND S O FT WA R E , E VE N I F A D VI S ED O F T HE

    P O S S I BI L I T Y O F S U C H D A M A G E .

    0.5 Bugs in the Book

    If youre having trouble working your way through the examples, post a detailedquestion to the programming Q&A site Stack Overflow

    http://stackoverflow.com/tags/magento

    with the following tags

    ma g en t o ma ge nt o - n of r i ll s

    Well be monitoring the site for any problems with code examples, and by askingyour questions in a public forum youll be helping the global Magento developer

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    8

  • 8/10/2019 No Frills Magento Layout

    10/164

    CHAPTER 0. NO FRILLS MAGENTO LAYOUT: INTRODUCTION

    community. Developers are often amazed when they find people across the worldare having the same problems they are, and often already have a solution ready

    to share.

    Additionally, each chapter will contain a link to a site online for discussionsspecific to each chapter. Youre not just getting a book, youre joining a com-munity.

    0.6 About the Author

    No Frills Magento Layout was written by Alan Storm. Alans an industryveteran with over 12 years on-the-job experience, and an active member of theMagento community. Hes written the go-to developer documentation for theMagento Knowledge Base, and is the author of the popular debugging extensionCommerce Bug. You can read more about Alan and his Magento products atthe following URLs

    http://alanstorm.com/

    http://store.pulsestorm.net/

    0.7 Lets Go

    Thats it for pleasantries, lets get started. In the first chapter were going tostart by creating Magento layouts using PHP code.

    Visit http://www.pulsestorm.net/nofrills-layout-introduction to join the discus-sion online.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    9

  • 8/10/2019 No Frills Magento Layout

    11/164

    Chapter 1

    Building Layouts

    Programmatically

    Before we can understand the layout system in its entirety, we need to under-stand its individual parts. With that in mind, well start with some simpleexamples. A Layout can be defined with the following phrase

    A Layout is a collection of blocks in a tree structure

    So, lets start by defining what a block is.

    A Magento block is an object with a toHtmlmethod defined. When this toHtmlmethod is called, it returns the string which should be output to the screen.

    Typically the screen means your web browser. In addition to having a toHtmlmethod, Magento blocks inherit from the Mage Core Block Abstract class. Thisclass contains a number of other useful block helper methods. Well get to theseeventually, but for now just think of a block as an object which has a toHtmlmethod, and when this toHtmlis called output is sent to the screen.

    Lets give this a try. If you installed the Nofrills Booklayoutmodule that camewith this book, you can open the following url on your system

    http://magento.example.com/nofrills booklayout/index/index

    which corresponds to the controller file at

    a p p / c o d e / l o c a l / N o f r i l l s / B o o k l a y o u t / c o n t r o l l e r s / I n d e x C o n t r o l l e r . p h p

    Well be adding our code examples to the indexAction methodp u b li c f u n c ti o n i n d e x Ac t i o n ( )

    {

    v a r _ d u m p ( _ _ M E T H O D _ _ ) ;

    }

    10

  • 8/10/2019 No Frills Magento Layout

    12/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    If you load the above URL with an unmodified extension, you should see amostly blank browser screen that looks something like Figure 1.1

    Figure 1.1

    First, well create a simple text block.

    p u b li c f u n c ti o n i n d e x Ac t i o n ( )

    {

    $ b l o ck = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b l o ck - > s e t T e x t ( " H e l l o W o r l d " ) ;

    e c h o $ b l o ck - > t o H t m l ( ) ;

    }

    Our first line instantiates a block object from the class Mage Core Block Text. Oursecond line sets the text we want to output, and the third line calls the toHtmlmethod, which returns our string and echos the output.

    If you reload your browser page, you should see the following output.

    H e l lo W o r ld

    So far so good. We now have an object oriented echo statement. In our exampleabove we instantiated a Mage Core Block Text object. When you call this type ofblocks toHtml method, it simply outputs whatever text has been set with thesetText method.

    Magento has literally hundreds of different types of block classes for every pos-

    sible need. The Magento core team subscribes to a style of development thatssimilar to Java and C# programming that says

    When in doubt, make a new class

    Each block type may have a slightly different implementation of how its toHtmlmethod is implemented. Fortunately, you dont need to know what every single

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    11

  • 8/10/2019 No Frills Magento Layout

    13/164

  • 8/10/2019 No Frills Magento Layout

    14/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    This allows you to rely on the base Magento design package, and only add filesthat you wish to change to your own packages and themes. See Appendix E for

    more information if youre interested in how this fallback system works. Heresa little trick to find out where Magento is loading any blocks template from.

    p u b li c f u n c ti o n i n d e x Ac t i o n ( )

    {

    $ b l o ck = n e w M a g e _ C or e _ B l o c k_ T e m p l at e ( ) ;

    $ b l o ck - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    v a r _ d u m p ( $ b l o c k - > g e t T e m p l a t e F i l e ( ) ) ;

    / / e c h o $b l o c k - > t o H t m l ( ) ;

    }

    By calling the blocks getTemplateFilemethod, were doing the same thing Ma-gento will when rendering the block. Running the above will result in

    s t r in g f r o n te n d / b a s e / d e fa u l t / t e m p la t e / h e l l o w or l d . p h t m l ( l e n g th = 4 7 )

    As mentioned, since we havent created a helloworld.phtml file, Magento fallsback to the base package/theme.

    1.3 Back to our Template

    Were going to assume youre working on a freshly installed Magento system,which means youll want to add your helloworld.phtml template to the defaultdesign package in the default theme. Create a file at the following location

    a p p / d e s i g n / f r o n t e n d / d e f a u l t / d e f a u l t / t e m p l a t e / h e l l o w o r l d . p h t m l

    Add something like the following to that file

  • 8/10/2019 No Frills Magento Layout

    15/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    Figure 1.2

    If you reload the page, you should see a hello world lorem ipsum, loaded fromthe template, (see Figure 1.2)

    Congratulations, youve created your first template block!

    1.4 Nesting Blocks

    Lets go back to our Layout definition

    A Layout is a collection of blocks in a tree structure

    Weve defined, very basically, what a block is, but what do we mean by in atree structure?

    Magento blocks are sort of like HTML nodes. For example, here

    < s p a n > L o r e m < / s p an >

    The

    tag is the parent node, and the is the child node. All blocksshare a similar relationship. Oversimplifying things a bit, this sort of paren-t/child relationship is known as a Tree in computer science circles.

    Lets consider our previous template block. Alter the phtml file so it containsthe following

  • 8/10/2019 No Frills Magento Layout

    16/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    < ? p hp e c ho $ t hi s - > g e t C h i l d H tm l ( t h e _ f i r st ) ; ? >

    T he s e co n d p a ra g ra p h i s h ar d - c o de d .

    Theres a few new concepts to cover here. First, youll notice weve droppedinto PHP code

    < ? p hp $ t hi s - > g e t C h i l d H tm l ( t h e _ f i r st ) ; ? >

    You may be wondering what $this is a reference to. If youll remember backto our definition of a template block, we said that each template block objecthas a phtml template file. So, when you refer to $thiswithin a phtml template,youre referring to the templates block object. If thats a little fuzzy future

    examples below should clear things up.Next, we have the getChildHtml method. This method will fetch a child block,and call its toHtmlmethod. This allows you to structure blocks and templatesin a logical way. So, with the above code in our template, lets reload the page,(seeFigure 1.3)

    Figure 1.3

    Our second hard-coded paragraph rendered, but nothing happened with our

    call to getChildHtml. Thats because we failed to add a child. Lets change ourcontroller action so it matches the following.

    p u b li c f u n c ti o n i n d e x Ac t i o n ( )

    {

    $ p a r a gr a p h _ b lo c k = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ p a r ag r a p h_ b l o ck - > s e t T e xt ( O n e p a r a g ra p h t o r u le t h em a l l . );

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    15

  • 8/10/2019 No Frills Magento Layout

    17/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    $ m a i n_ b l o c k = n e w M a g e _ C or e _ B l o c k_ T e m p l at e ( ) ;$ m a i n _ b l o c k - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    $ m a i n _ b l o c k - > s e t C h i l d ( t h e _ f i r s t , $ p a r a g r a p h _ b l o c k ) ;

    e c h o $ m a i n _ b l o ck - > t o H t m l ( ) ;

    }

    Well dissect this chunk by chunk. First, we have the following

    $ p a r a g ra p h _ b lo c k = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ p a r ag r a p h_ b l o ck - > s e t T ex t ( O n e p a r a gr a p h t o r u le t h e m a l l . );

    Here weve created a simple text block. Weve set its text so that when theblock is rendered, it will output the sentence One paragraph to rule them all..Then, as we did before,

    $ m a i n _b l o c k = n e w M a g e _ C o re _ B l o c k_ T e m p l a te ( ) ;

    $ m a i n _ b l o ck - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    we define a template block, and point it toward our hello world template. Finally(and heres the key)

    $ m a i n _ b l o c k - > s e t C h i l d ( t h e _ f i r s t , $ p a r a g r a p h _ b l o c k ) ;

    Here we call a method we havent see before, called setChild. Here were tellingMagento that the $paragraph blockis a child of the $main block. Weve also giventhat block a name (or alias) of the first. This name is how well refer to theblock later, and what well pass into our call to getChildHtml

    < ? p hp e c h o $ t hi s - > g e t C h i l d H tm l ( t h e _ f i rs t ) ; ? >

    Expressed as a generic XML tree, the relationship between blocks might looklike

    < p a r a g r a p h _ b l o c k n a m e = " t h e _ f i r s t " > < / p a r a g r a p h _ b l o c k >

    Or maybe (getting a bit ahead of ourselves)

    < b l o c k t y p e = " c or e / t e m p l at e " n a me = " r o o t " t e m p la t e = " h e l l o wo r l d . p h t ml " >

    < b l o ck t y p e = " c or e / t e x t " n a me = " t h e _ f i r st " >

    < a c t i on n a m e = " s e tT e x t " >

    < t ex t > O ne p a ra g ra p h t o r ul e t he m a ll < / t ex t >

    < / b l o c k >

    < / b l o c k >

    A block may have an unlimited number of children, and because were dealingwith PHP 5 objects, changes made to the block after it has been appended willcarry through to the final rendered object. Try the following code

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    16

  • 8/10/2019 No Frills Magento Layout

    18/164

  • 8/10/2019 No Frills Magento Layout

    19/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    1.5 Advanced Block Functionality

    Theres a few more bits of block functionality we should cover before movingon.

    The first thing well cover is creating your own block classes. There will betimes where you want a block with some custom programmatic functionality.While it may be tempting to use a standard template block and then includeall your logic in the phtml template, the preferred way of doing this is to createa Magento module for adding your own code to the system, and then addingyour own block classes that extend the existing classes.

    Were not going to cover creating a new module here, although if youre inter-ested in learning the basics then checkout Appendix C. Instead, well have youcreate your custom block in the NoFrills Booklayoutmodule.

    So, we just spent a lot of effort to create a hello world block. Lets take whatweve done so far, and create a hello world block. The first thing well want todo is create a new class file at the following location, with the following contents

    # F i l e : a p p / c o de / l o c a l / N o f r il l s / B o o k l a yo u t / B l o c k / H e l lo w o r ld . p h p

  • 8/10/2019 No Frills Magento Layout

    20/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    Next, lets add the following method to our new class,

    c l a ss N o f r i l l s_ B o o k l a yo u t _ B l o c k_ H e l l o w or l d e x t en d s M a g e _ C or e _ B l o c k_ T e m p l at e

    {

    p u b l ic f u n c ti o n _ c o n st r u c t ( )

    {

    $ t h i s - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    r e t ur n p a r en t : : _ c o n s t ru c t ( ) ;

    }

    }

    and remove the setTemplateclass in our controller.

    p u b li c f u n c ti o n h e l l o b lo c k A c ti o n ( )

    {

    $ b l o ck _ 1 = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b l oc k _1 - > s e t T ex t ( T h e f i r st s e n t en c e . ) ;

    $ b l o ck _ 2 = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b l oc k _2 - > s e t T ex t ( T h e s e c on d s e n t en c e . ) ;

    $ m a i n_ b l o c k = n e w N o f r i l l s_ B o o k l a y ou t _ B l o c k_ H e l l o w or l d ( ) ;

    // $m a i n _ b l o c k - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l );

    $ m a i n _ b l o c k - > s e t C h i l d ( t h e _ f i r s t , $ b l o c k _ 1 ) ;

    $ m a i n _ b l o c k - > s e t C h i l d ( t h e _ s e c o n d , $ b l o c k _ 2 ) ;

    e c h o $ m a i n _ b l o ck - > t o H t m l ( ) ;

    }

    A page refresh should result in the same exact page.

    Every block class can define an optional pseudo-constructor. This is a methodthats called whenever a new block of this type is created, but that is separate

    from PHPs standard constructor. What weve done is ensure that our blockalways has a template set.

    p u b l ic f u n c ti o n _ c o n st r u c t ( )

    {

    $ t h i s - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    r e t ur n p a r en t : : _ c o n s t ru c t ( ) ;

    }

    Theres a few other special methods you can define in a block class. The firstthat were interested in is beforeToHtml. When we call toHtmlon our block, thismethod is called immediately before the block content is rendered. Theresalso a corresponding afterToHtml($html) method which is called after a blockis rendered, and is passed the completed HTML string. Were going to use

    the beforeToHtml method to automatically add our two child blocks, makingeverything self contained.

    c l a ss N o f r i l l s_ B o o k l a yo u t _ B l o c k_ H e l l o w or l d e x t en d s M a g e _ C or e _ B l o c k_ T e m p l at e

    {

    p u b l ic f u n c ti o n _ c o n st r u c t ( )

    {

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    19

  • 8/10/2019 No Frills Magento Layout

    21/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    $ t h i s - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    r e t ur n p a r en t : : _ c o n s t ru c t ( ) ;

    }

    p u b l ic f u n c ti o n _ b e f o re T o H t ml ( )

    {

    $ b l o ck _ 1 = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b lo c k _1 - > s e t T e xt ( T h e f i r st s e n t en c e . ) ;

    $ t hi s - > s e t C h i l d ( t h e _f i r s t , $ b l o ck _ 1 ) ;

    $ b l o ck _ 2 = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b lo c k _2 - > s e t T e xt ( T h e s e c o nd s e n t en c e . ) ;

    $ t hi s - > s e t C h i l d ( t h e _ se c o n d , $ b l o ck _ 2 ) ;

    }

    }

    This will let us remove the extraneous code from our controller

    p u b li c f u n c ti o n h e l l o b lo c k A c ti o n ( ){

    $ m a i n_ b l o c k = n e w N o f r i l l s_ B o o k l a y ou t _ B l o c k_ H e l l o w or l d ( ) ;

    e c h o $ m a i n _ b l o ck - > t o H t m l ( ) ;

    }

    Again, a page refresh should result in the exact same page. Weve gone fromhaving to manually create our hello world block with 10 or so lines of codeto completely encapsulating its functionality and output in 2 lines. This is apattern youll see over and over again in Magento.

    1.6 Block Methods

    The other thing we want to cover is calling, and adding, custom methods toyour phtml templates. Go to your helloworld.phtml file and change the titleline so it matches the following.

    < ! - - < h1 > H e l l o W o rl d < / h 1 > - - >

    < h 1 > < ? p hp e c ho $ t hi s - > f e t c h T i t l e ( ); ? > < / h1 >

    If you reload your page with this in place, youll get the following error

    I n v al i d m e t ho d N o f r i l l s_ B o o k l a yo u t _ B l o c k_ H e l l o w or l d : : f e t c h T i tl e ( A r r a y

    (

    )

    )

    As previously mentioned, if you use the $thiskeyword in your template, yourereferring to a templates parent block object. Lets add a method that returnsthe page title

    c l a ss N o f r i l l s_ B o o k l a yo u t _ B l o c k_ H e l l o w or l d e x t en d s M a g e _ C or e _ B l o c k_ T e m p l at e

    {

    p u b l ic f u n c ti o n _ c o n st r u c t ( )

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    20

  • 8/10/2019 No Frills Magento Layout

    22/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    {

    $ t h i s - > s e t T e m p l a t e ( h e l l o w o r l d . p h t m l ) ;

    r e t ur n p a r en t : : _ c o n s t ru c t ( ) ;}

    p u b l ic f u n c ti o n _ b e f o re T o H t ml ( )

    {

    $ b l o ck _ 1 = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b lo c k _1 - > s e t T e xt ( T h e f i r st s e n t en c e . ) ;

    $ t hi s - > s e t C h i l d ( t h e _f i r s t , $ b l o ck _ 1 ) ;

    $ b l o ck _ 2 = n e w M a g e _ C or e _ B l o ck _ T e x t ( ) ;

    $ b lo c k _2 - > s e t T e xt ( T h e s e c o nd s e n t en c e . ) ;

    $ t hi s - > s e t C h i l d ( t h e _ se c o n d , $ b l o ck _ 2 ) ;

    }

    p u b l ic f u n c ti o n f e t c hT i t l e ( )

    {

    r e t ur n H e l lo F a n cy W o r ld ;}

    }

    Reload the page with the above Nofrills Booklayout Block Helloworldin place, andyoull see your page with its new title.

    This is the preferred way to create templates with dynamic data in Magento.Your phtmlfile should contain

    1. HTML/CSS/Javascript code

    2. Calls to echo

    3. Looping and control structures

    4. Calls to block methods

    Any PHP more complicated than the above should be put in block methods.This includes calls to Magento models to read back data which was saved in thecontroller layer.

    1.7 Enter the Layout

    Coming back again to our definition of a Layout

    A Layout is a collection of blocks in a tree structure

    We now know what a block is and what a block can do. We understand how

    blocks are organized in a tree like structure. The only thing that leaves us tocover is the layout object itself.

    A layout object, (instantiated from a Mage Core Model Layout class)

    Is a wrapper object for interacting with your blocks.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    21

  • 8/10/2019 No Frills Magento Layout

    23/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    Provides helper methods for creating blocks

    Allows you to designate which block should start the rendering for a page Provides a mechanism for loading complex layouts described by XML files

    Lets take a look at some layout examples. Add the following action to ourcontroller

    # h t t p : / / m a g e n t o . e x a m p l e . c o m / n o f r i l l s _ b o o k l a y o u t / i n d e x / l a y o u t

    p u b li c f u n c ti o n l a y o u tA c t i o n ( )

    {

    $ l a yo u t = M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;

    $ b l o ck = $ l ay o ut - > c r e a t e Bl o c k ( c o re / t e m p l a t e , r oo t ) ;

    $ b l o ck - > s e t T e m p l a t e ( h e l l o w o r l d - 2 . p h t m l ) ;

    e c h o $ b l o ck - > t o H t m l ( ) ;

    }

    Next, create a file named helloworld-2.phtmlthats in the same location as yourhelloworld.phtml template.

  • 8/10/2019 No Frills Magento Layout

    24/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    just substitue

    $ o = n e w M a g e _ F o o _ M o d el _ B a r ( ) ;

    in your mind.

    1.7.1 Whats a Singleton!?

    A singleton is a fancy object oriented programming term for an object that mayonly be instantiated once. The first time you instantiate it, a new object will becreated. However, if you attempt to instantiate the object again, rather thancreate a new object, the originally created object will be returned.

    A singleton is used when you only want to create a single instance of any typeof object. Magento assumes youll only want to render one HTML page per

    request (probably a safe assumption), and by using a singleton its ensuredyoure always getting the same layout object.

    If all that went over your head dont worry. All you need to know is wheneveryou want to get a reference to your layout object, use

    $ l a yo u t = M a ge : : g e t S i n g l et o n ( c o r e / l a yo u t ) ;

    1.8 Back to the Code

    Next up we have the line

    $ b l oc k = $ l ay o ut - > c r e a t e Bl o c k ( c o r e / t e mp l a t e , r oo t ) ;

    This line creates aMage Core Template Block object namedroot (well get to the whyof root in a bit) by calling the createBlockmethod on our newly instantiatedlayout object.

    Again, in place of a class name, we have the core/templateclass alias. Becausewere using the class alias to instantiate a block, this translates to

    M a g e _ C o r e _ B l o c k _ T e m p l a t e

    Again, check Appendix B if youre interested in how class aliases are resolved.Whenever we use a class alias for the remainder of this book, well let you knowthe real PHP class.

    Everything else from here on out should look familiar. The following$ b l o ck - > s e t T e m p l a t e ( h e l l o w o r l d - 2 . p h t m l ) ;

    e c h o $ b l o c k - > t o H t m l ( ) ;

    sets our block template, and renders the block using its toHtml method. Letsuse a class alias to instantiate our custom block from the previous examples

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    23

  • 8/10/2019 No Frills Magento Layout

    25/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    / / c l a ss a l i as n o f r i l l s_ b o o k l ay o u t / h e l l o w or l d i s t r a n s la t e d i n to

    / / t h e c l a ss n a me N o f r i l l s_ B o o k l a y ou t _ B l o c k_ H e l l o w or l d

    p u b li c f u n c ti o n l a y o u tA c t i o n ( ){

    $ l a yo u t = M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;

    $ b l o ck = $ l ay o ut - > c r ea t e B lo c k ( n o f r i l l s _b o o k l a yo u t / h e l l o w o rl d , r o o t ) ;

    e c h o $ b l o ck - > t o H t m l ( ) ;

    }

    Reload the page, you should see our original block.

    1.9 Whos the Leader

    Give our next example a try

    p u b li c f u n c ti o n l a y o u tA c t i o n ( ){

    $ l a yo u t = M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;

    $ b l o ck = $ l ay o ut - > c r ea t e B lo c k ( n o f r i l l s _b o o k l a yo u t / h e l l o w o rl d , r o o t ) ;

    $ l a y o ut - > a d d O u t p u t B l o c k ( r o o t ) ;

    $ l a y o ut - > s e t D i r e c t O u t p u t ( t r u e ) ;

    $ l a y o ut - > g e t O u t p u t ( ) ;

    }

    Refresh the page, and you should see the same output as your did before.

    What weve done here is replace our call to the blocks toHtmlwith the following

    $ l a y o ut - > a d d O u t p u t B l o c k ( r o o t ) ;

    $ l a y o ut - > s e t D i r e c t O u t p u t ( t r u e ) ;

    $ l a y o ut - > g e t O u t p u t ( ) ;

    The call to addOutputBlocktells our layout block thatthisis the block that shouldstart the page rendering process. Following that is a call to getOutput, which isthe call that actually starts the page rendering process. Every time you usecreateBlock to create an object, the Layout object will know about that block.Thats why we gave it a name earlier.

    The call to setDirectOutput is us telling the Layout object that it should justautomatically echo out the results of the page. If we wanted to capture theresults as a string instead, wed just use

    $ l a y o ut - > a d d O u t p u t B l o c k ( r o o t ) ;

    $ l a y o ut - > s e t D i r e c t O u t p u t ( f a l s e ) ;

    $ o u t p u t = $ l a y o ut - > g e t O u t p u t ( ) ;

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    24

  • 8/10/2019 No Frills Magento Layout

    26/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    1.10 Method Chaining

    Nows probably a good time to mention a PHP feature that Magento makesextensive use of called method chaining. Lets replace our code from above withthe following.

    p u b li c f u n c ti o n l a y o u tA c t i o n ( )

    {

    $ l a yo u t = M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;

    $ b l o ck = $ l ay o ut - > c r ea t e B lo c k ( n o f r i l l s _b o o k l a yo u t / h e l l o w o rl d , r o o t ) ;

    e c h o $ l a y o ut - > a d d O u t p u t B l o c k ( r o o t ) - > s e t D i r e c t O u t p u t ( f a l s e ) - > g e t O u t p u t ( ) ;

    }

    Youll notice that weve trimmed a few lines from the code, but that were usinga funky syntax in that last line.

    e c h o $ l a y o u t - > a d d O u t p u t B l o c k ( r o o t ) - > s e t D i r e c t O u t p u t ( f a l s e ) - > g e t O u t p u t ( ) ;

    This is method chaining. Its not a Magento feature per se, but its a feature ofPHP thats become much more popular as applications start leveraging PHP 5OOP capabilities.

    If a call to a method returns an object, PHP lets you chain a another methodcall on the end for brevity. This can be repeated as long as each method callreturns an object. The above is equivalent to the following

    $ b l oc k = $ l ay o ut - > a d d O u t p ut B l o c k ( r o ot ) ;

    $ b l o ck - > s e t D i r e c t O u t p u t ( f a l s e ) ;

    e c h o $ b l o c k - > g e t O u t p u t ( ) ;

    Youll also see chaining syntax that spans multiple lines

    $ l a y o ut - > a d d O u t p u t B l o c k ( r o o t )- > s e t D i r e c t O u t p u t ( f a l s e )

    - > g e t O u t p u t ( ) ;

    Again, this isnt anything thats specific to Magento. Its just a pattern thatsbecoming more popular with PHP developers as PHP 5 style objects are usedmore and more. Magentoenablesthis syntax by having most of its set, create,and add methods return an appropriate object. Youre not required to use it,but get used to seeing it if you spend any time with core or community modules

    1.11 A Full Page Layout

    From here on out were going to start using a special block weve created in theNofrills module you installed. Its called

    n o f r i l l s _ b o o k l a y o u t / t e m p l a t e

    N o f r i l l s _ B o o k l a y o u t _ B l o c k _ T e m p l a t e

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    25

  • 8/10/2019 No Frills Magento Layout

    27/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    The block is identical to the Core template block, with one exception.

    p u b li c f u n c ti o n f e t c hV i e w ( $ f i l e Na m e )

    {

    / / i gn o re s f il e n am e , j us t u se s a s i mp l e i n cl u de w it h t e mp l at e n am e

    $ t h i s - > s e t S c r i p t P a t h (

    M a ge : : g e t M o d u l eD i r ( , N o f r i l l s_ B o o k l ay o u t ) .

    DS .

    d e s i g n

    );

    r e t u rn p a r en t : : f e t c h Vi e w ( $ t hi s - > g e t T e m p l at e ( ) ) ;

    }

    Weve overridden the fetchView function in our template with the code above.What this does is move the base folder for templates from

    a p p / d e s i g n

    to a folder in our local module hierarchy.a p p / c o d e / l o c a l / N o f r i l l s / B o o k l a y o u t / d e s i g n

    This has allowed us to package our template files in the same folder as our PHPfiles, and save you from a lot of copy/paste

    Lets open up the URL that corresponds to the Layoutdemo controller

    # U R L : h t tp : / / m a g e n to . e x a m p l e . c o m / n o f r il l s _ b oo k l a y o ut / l a y o u t d e mo

    # F i l e : a p p / c od e / l o c a l / N o f ri l l s / B o o k l ay o u t / c o n t r ol l e r s / L a y o u t de m o C o n tr o l l e r . p h p

    You should see a browser screen that looks like Figure 1.4

    Figure 1.4

    If you view the source of this page, youll see we have a full (if very basic) HTMLpage structure. Lets take a look at the code we used to create the layout andblocks necessary to pull this off.

    # F i l e : a p p / c od / l o c a l / N o f ri l l s / B o o k l ay o u t / c o n t r ol l e r s / L a y o u t de m o C o n tr o l l e r . p h pc l a ss N o f r i l l s_ B o o k l a y ou t _ L a y o ut d e m o C o n tr o l l e r

    e x t e n d s M a g e _ C o r e _ C o n t r o l l e r _ F r o n t _ A c t i o n

    {

    p u b l ic f u n c ti o n _ i n i tL a y o u t ( )

    {

    $ la yo ut = M ag e :: g et Si ng le to n ( co re / la yo ut );

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    26

  • 8/10/2019 No Frills Magento Layout

    28/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    $ l a y o ut - > a d d O u t p u t B l o c k ( r o o t ) ;

    $ a d d i ti o n a l _ he a d = $ l ay o ut - > c r e a t e Bl o c k ( n o f r i l l s _ b o o k l a y o u t / t e m p l a t e , a d d i t i o n a l _ h e a d )

    - > s e t T e m p l a t e ( s i m p l e - p a g e / h e a d . p h t m l ) ;

    $ s i d e b a r = $ l a y o ut - > c r e a t e B l o c k ( n o f r i l l s _ b o o k l a y o u t / t e m p l a t e , s i d e b a r )

    - > s e t T e m p l a t e ( s i m p l e - p a g e / s i d e b a r . p h t m l ) ;

    $ c o n te n t = $ l ay o ut - > c r e a t e Bl o c k ( c o re / t e x t _ l i st , c o n t en t ) ;

    $ r o ot = $ l ay o ut - > c r e a t e Bl o c k ( n o f r i l ls _ b o o k la y o u t / t e m p l at e , r o o t )

    - > s e t T e m p l a t e ( s i m p l e - p a g e / 2 c o l . p h t m l )

    - > i n s e r t ( $ a d d i t i o n a l _ h e a d )

    - > i n s e r t ( $ s i d e b a r )

    - > i n s e r t ( $ c o n t e n t ) ;

    r e t ur n $ l a y ou t ;}

    p u b l ic f u n c ti o n i n d e xA c t i o n ( )

    {

    $ l a y ou t = $ t hi s - > _ i n i t L a y ou t ( ) ;

    $ t e xt = $ l ay o u t - > c r e a t e Bl o c k ( c o re / t e x t , w o rd s ) ;

    $ te xt - > s e t Te x t ( I t w as t he b es t o f t im es , i t w as t he B L UR S T ?! o f t i me s ? );

    $ c o n t e n t = $ l a y o ut - > g e t B l o c k ( c o n t e n t ) ;

    $ c o n t e nt - > i n s e r t ( $ t e x t ) ;

    $ l a y o ut - > s e t D i r e c t O u t p u t ( t r u e ) ;

    $ l a y o ut - > g e t O u t p u t ( ) ;

    e x i t ;

    }

    }

    Again, we have some new concepts well need to cover here.

    1.12 Initializing the Layout and Setting Content

    The first thing youll notice is the initLayoutlayout method. Were using thiscontroller method to setup a base layout object that has common components(like navigation, some HTML, etc.) defined. This allows many differentcontroller methods to share the same basic layout, without us having to rewrite

    the setup code every time. Instead, all each action would need to do is call$ l a yo u t = $ t hi s - > _ i n i t L a y o ut ( ) ;

    and a base/shared layout would already be created.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    27

  • 8/10/2019 No Frills Magento Layout

    29/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    1.13 Insert vs. Set

    You also probably noticed were not using the setChildmethod to add blocks toour layout. Instead, were using the insertto add child blocks to other blocks.

    - > i n s e r t ( $ a d d i t i o n a l _ h e a d )

    The insertmethod is the preferred method for adding child blocks to an existingblock. Theres a bit of redundancy in the setChildmethod, as it requires you topass in a name for your block.

    $ b l o ck - > s e t C h i l d ( b l o c k _ n a m e , $ b l o c k ) ;

    However, the insertmethod will automatically use the name you set when youcreated it (the following code created a block named sidebar)

    $ l a y o u t - > c r e a t e B l o c k ( n o f r i l l s _ b o o k l a y o u t / t e m p l a t e , s i d e b a r ) ;

    There are a few other problems with using setChild in a public context; as ofCE 1.4.2 it still doesnt add blocks to the internal sortedBlocksarray, which willcause problems down the road, (see Chapter 5 for more information).

    Stick with insertmethod and youll be a happy camper.

    1.14 Getting a Reference and Text List

    So, the initLayout method serves as a central location for instantiating a baselayout object. Templates are set, and a complete layout object with an empty

    content node is returned. Well want to turn our attention to the followingcode.

    $ t e xt = $ l ay o ut - > c r e a t e Bl o c k ( c o re / t e x t , w o rd s ) ;

    $ te xt - > s e t T ex t ( It w as t he b e st o f t im es , i t w as t he B L UR S T ?! o f t i me s ? );

    $ c o n te n t = $ l ay o ut - > g e t B l oc k ( c o n t e nt ) ;

    $ c o n t e n t - > i n s e r t ( $ t e x t ) ;

    The first two lines should look familiar. Were creating a simple core/text(Mage Core Block Text) block that looks like it was written by an infinite num-ber of monkeys - 1. The next set of lines is far more interesting. The getBlockmethod allows you to re-obtain a reference to any block thats been added tothe layout (including those added using createBlock).

    What this code does is get a reference to the content block that was added ininitLayout, and then add our new content block to it. The getBlockmethod is

    what allows us to centralize the creation of a general layout, and then customizeit further for any specific actions needs.

    Lets look back up at the creation of our block named content.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    28

  • 8/10/2019 No Frills Magento Layout

    30/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    $ c o n te n t = $ l ay o ut - > c r e a t e Bl o c k ( c o re / t e x t _ l i st , c o n t en t ) ;

    Youll notice we used the class alias core/text list here, which corresponds tothe class Mage Core Block Text List. Text list blocks have a slightly deceptivename, as you dont set their text. Instead, what a core/text listblock does isautomaticallyrender all child blocks that have been added to it.

    This feature of the core/text listblock is what allows us to add a block namedcontent and just start inserting blocks into it. Any block we add will be auto-matically rendered.

    1.15 A Recap and a Dilema

    Look back one last time at our definition of a Layout

    A Layout is a collection of blocks in a tree structure

    We appear to have covered everything a layout is. We know what a block is, weknow how to create a nested structure of blocks, and we now understand howthe Layout ob ject provides command and control for the entire show. Wevealso seen how a generic layout can be built, and then added to depending onour needs.

    However, by answering these questions, weve created a new one. HowshouldMagento create the layouts needed for each page? Consider our example codeabove where we abstracted the creation of the Layout object to a initLayoutmethod. This made sense for the tutorials, but Magento core code contains over180 controllers. If we put layout instantiation in each controller, that means

    anytime the core team wanted to make a change to the base layout wed needto update over 180 files. These different initLayoutfunctions would inevitablystart to differ in slight ways, eventually causing incompatibility.

    The next choice would be to create a separate, centralized, master Layout objectfor the base layout. Core system programmers could then get a reference to theobject, and add to it as need be. This solves some problems, but creates asituation where were either relying on system programmers whenever designersneed to change something, or letting designers into core system code to changehighly abstracted PHP code they may not understand. While services basedagencies have long used designer/coders and coder/designers, this metaphorhasnt penetrated as deeply in the computer science world, which prefers a layerof separation between the two worlds.

    Magentos solution to this situation was to create a system where designerscould configure what layout they wanted for any particular URL request inMagento. This is the Layout XML system that many of you are already familiarwith, and the system that well be diving into in our next chapter.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    29

  • 8/10/2019 No Frills Magento Layout

    31/164

    CHAPTER 1. BUILDING LAYOUTS PROGRAMMATICALLY

    Visit http://www.pulsestorm.net/nofrills-layout-chapter-one to join the discus-sion online.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    30

  • 8/10/2019 No Frills Magento Layout

    32/164

    Chapter 2

    XML Page Layout Files

    The core problem the Magento Layout XML system sets out to solves is

    How do we allow designers and theme developers to configure alayout, but still offer them full control over the HTML output ifthey need/want it

    So why XML? XML gets used for a lot of things. If youve been doing webdevelopment for a while you probably think of XML as a generic documentformat. While thatsoneof the things XML can be used for, software engineersand computer scientists have other uses for it.

    The Magento XML Layout format is less a document format, and more a mini-programming language. The Magento core team created a special format ofXML files that fully describes the process of creating blocks programmaticallythat was described in the previous chapter. There is no public schema or DTDfor this dialect of XML, but dont worry, by the time were through with thischapter youll have the format down cold.

    The Magento Layout XML System is made up of multiple independent pieces.It may seem like some of what were doing is more of a hassle than just usingPHP to create our blocks. However, once youve seen all the pieces, and howthose pieces fit together, the advantages of the system should be apparent.

    All of which is a fancy way of saying, Hang in There. This is new, thisis different than what youre used to, but its no harder than any other webdevelopment youve learned before.

    Finally, while not 100% necessary, the content of this chapter assumes youvebeen through Chapter 1. Even if youre a master at creating blocks program-matically, you may want to skim through the previous chapter before venturingon.

    31

  • 8/10/2019 No Frills Magento Layout

    33/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    2.1 Hello World in XML

    Well be working in UpdateController.phpin this chapter, which may be accessedat the following URL/file

    h t t p : / / m a g e n t o . e x a m p l e . c o m / n o f r i l l s _ b o o k l a y o u t / u p d a t e

    a p p / c o d e / l o c a l / N o f r i l l s / B o o k l a y o u t / c o n t r o l l e r s / U p d a t e C o n t r o l l e r . p h p

    The first type of XML tree Magento uses is called the Page Layout. We say treeinstead of file, as the Page Layout XML is normally generated on the fly. Weregoing to create a few Page Layouts manually to get an idea of how they work.

    In the previous chapter, we created a Hello World block with a class alias ofnofrills booklayout/helloworld (corresponding to the class Nofrills Booklayout Block Helloworld).Lets start by creating a Page Layout that uses this block.

    First, heres the XML well use

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / h e l l o w o r ld " n a m e = " r oo t " o u t pu t = " t o H t ml " / >

    We have an XML node with a root node named layout. Within the root nodeis a single block node with three attributes; type, name, and output.

    The type attribute is where we specify the class alias of the block wed like toinstantiate. The nameattribute allows us to set a name for the block which canbe used later to get a reference. The output="toHtml" attribute/value pair tellsthe layout system that this is the block which should start output.

    The Page Layout XML above is roughly equivalent to the following PHP code

    $ l a yo u t = n e w M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;$ l a y o u t - > c r e a t e B l o c k ( n o f r i l l s _ b o o k l a y o u t / h e l l o w o r l d , r o o t ) ;

    $ l a y o u t - > a d d O u t p u t B l o c k ( r o o t , t o H t m l )

    Youll notice weve passed in a second parameter (toHtml) to the addOutputBlockmethod. This is an optional parameter that tells the layout object whichmethod on the output block should be be used to kick off output. If you lookat its definition, it normally defaults to toHtml

    p u b li c f u n c ti o n a d d O u tp u t B l o ck ( $ b l o c kN a m e , $ m e th o d = t o H t ml )

    {

    //$t h is - > _ o u t p ut [ ] = a r r ay ( $blockName , $m e t h o d ) ;

    $ t hi s - > _ o u t p u t [ $ b l o c kN a m e ] = a r r ay ( $ b l o c kN a m e , $ m e t ho d ) ;

    r e t u rn $ t h is ;

    }

    In practice youll never set this optional parameter, but were including it hereto make it more clear what the output attribute in the XML node above is doing

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    32

  • 8/10/2019 No Frills Magento Layout

    34/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    2.2 An Interesting use of the Word Simple

    Lets load our XML into the layout object and use it to generate our output.Edit the indexActionmethod in UpdateController.phpso it matches the following

    p u b li c f u n c ti o n i n d e x Ac t i o n ( )

    {

    $ l a yo u t = M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;

    $ x m l = s i m p l e xm l _ l o a d_ s t r i n g ( < l ay o ut >

    < b l o ck t y pe = " n o f r i l l s _ b oo k l a y o ut / h e l l o w o r ld "

    n a me = " r o o t " o u t p ut = " t o H t m l " / >

    < / l a y o ut > , M a g e _ C o r e _ M o d e l _ L a y o u t _ E l e m e n t ) ;

    $ l a y o ut - > s e t X m l ( $ x m l ) ;

    $ l a y o ut - > g e n e r a t e B l o c k s ( ) ;

    e c h o $ l a y o ut - > s e t D i r e c t O u t p u t ( t r u e ) - > g e t O u t p u t ( ) ;

    }

    Load the code above in a browser at

    h t t p : / / m a g e n t o . e x a m p l e . c o m / n o f r i l l s _ b o o k l a y o u t / u p d a t e

    and you should see your Hello World block.

    The first thing that may look a little unfamiliar about the code above is thefragment that creates our simple XML object.

    $ x m l = s i m p l e xm l _ l o a d _s t r i n g ( < l ay o ut >

    < b l o c k t y p e = " n o f r il l s _ b oo k l a y o ut / h e l l o w o r ld " n a m e = " r oo t " o u t pu t = " t o H t ml " / >

    < / l a y ou t > , M a g e _ C o r e _ M o d e l _ L a y o u t _ E l e m e n t ) ;

    You may have never seen a SimpleXML node created with that second parameter

    M a g e _ C o r e _ M o d e l _ L a y o u t _ E l e m e n t

    One of SimpleXMLs lesser known features is the ability to tell PHP to use auser defined class to represent the nodes. By default, a SimpleXML node is aobject of type SimpleXMLElement, which is a PHP built-in. By using the syntaxabove, the Magento core code is telling PHP

    Make our simple XML nodes objects of type Mage Core Model Layout Elementinstead of type SimpleXMLElement

    If you look at the inheritance chain, you can see that the Mage Core Model Layout Elementclass has SimpleXMLElementas an ancestor.

    c l a ss M a g e _ C o re _ M o d e l _L a y o u t _ El e m e n t e x t e nd s V a r i e n _ Si m p l e x ml _ E l e m en t { . . .}

    c l a ss V a r i e n _S i m p l e x ml _ E l e m en t e x t e nd s S i m p l e XM L E l e me n t { . . .}

    So, the Magento provided class name extends SimpleXMLElement. That means allnormal SimpleXML functionality is preserved.

    If you tried to use setXmlwith a normal SimpleXMLElement, youd end up with anerror that looks something like this

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    33

  • 8/10/2019 No Frills Magento Layout

    35/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    R e c o v er a b l e E r r or : A r g u me n t 1 p a s se d t o V a r i e n _S i m p l e x ml _ C o n f ig : : s e t X m l ( )

    mu st be an in s t an c e of V a r i e n _ S i m p l e x m l _ E l e me n t , in s t an c e of

    S i m p l e XM L E l e me n t g i v en

    Thats because Magento uses PHPs type hinting features to ensure that a nor-mal SimpleXMLElement based object cant be used.

    / / n o t ic e t h e V a r i e n _ Si m p l e x ml _ E l e m en t t y p e h i n t in g

    p u b li c f u n c ti o n s e t Xm l ( V a r i e n _ S i mp l e x m l _ El e m e n t $ n o de )

    {

    .. .

    This is another example of Magentos object oriented system design. Some ofyou are probably thinking Thats nuts! Why would you want to do this?By providing a custom class here, we gain the ability to add custom methods toany XML node. For example, if we were using the default SimpleXMLElementnode, every time we wanted to grab a blocks name attribute wed need to dosomething like this

    $ t a g Na m e = ( s t r i ng ) $ n o de - > g e t N am e ( ) ;

    i f ( b l o c k ! = = $ t a g N am e & & r e f e r en c e ! = = $ t a gN a m e | | e m p ty ( $ n o d e [ n a me ] ) ) {

    $ n am e = f al s e ;

    }

    $ n a me = ( s t r i ng ) $ n o d e [ n a me ] ;

    Using the SimpleXML custom class feature, we can define a method on our classto do this for us

    p u b li c f u n c ti o n g e t B l oc k N a m e ( )

    {

    $ t a g Na m e = ( s t r i ng ) $ t h is - > g e t N am e ( ) ;

    i f ( b l o c k ! = = $ t a g N am e & & r e f e r en c e ! = = $ t a gN a m e | | e m p ty ( $ t h i s [ n a me ] ) ) {

    r e t ur n f a l se ;

    }r e t u rn ( s t r i n g ) $ t hi s [ n a m e ] ;

    }

    and then use it wherever we want, resulting in cleaner end-user code which iseasier to read and understand

    $ n a me = $ n od e - > g e t B l o c k N am e ( ) ;

    If youre not convinced, a little paraphrased Tennyson might help you along theway

    Ours is not to question why/Ours is but to do or die

    2.3 Adding the XML, Generating the Blocks

    So, that little foray in lesser known PHP features complete, the next bit itpretty straight forward. Our Layout object is responsible for managing ourPage Layout XML

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    34

  • 8/10/2019 No Frills Magento Layout

    36/164

  • 8/10/2019 No Frills Magento Layout

    37/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    The second thing youll notice is weve replaced the hard coded XML elementclass

    M a g e _ C o r e _ M o d e l _ L a y o u t _ E l e m e n t

    with a call to

    M a g e : : g e t C o n f i g ( ) - > g e t M o d e l C l a s s N a m e ( c o r e / l a y o u t _ e l e m e n t )

    While current versions of Magento use a Mage Core Model Layout Element, its pos-sible that a future version may change this. Because of that, Magento engineersstore and read this class name from a config file. When possible, its best tofollow the same conventions you see in Magento core code to ensure maximumcompatibility with future versions. Again, this is something you wont needto concern yourself with while using the Layout system, rather its somethingyoud want to understanding if youre working on extending it.

    Alright! Lets take a look at the layout we just rendered and the XML thatcreated it, (see Figure 2.1 )

    Figure 2.1

    If you look at the complex.xmlfile (bundled with the Chapter 2 module code),

    a p p / c o d e / l o c a l / N o f r i l l s / B o o k l a y o u t / p a g e - l a y o u t s / c o m p l e x . x m l

    youll see the following

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / t e m p l a t e " n a m e = " r oo t "

    t e m p l a t e = " s i m p l e - p a g e / 2 c o l . p h t m l " o u t p u t = " t o H t m l " >

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / t e m p l a t e " n a me = " a d d i t i o n a l_ h e a d "

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    36

  • 8/10/2019 No Frills Magento Layout

    38/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    t e m p l a t e = " s i m p l e - p a g e / h e a d . p h t m l " / >

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / t e m p l a t e " n a me = " s i d e b a r " >< a c t i on m e t h od = " s e t T e m p l at e " >

    simple -page /sid ebar. phtml

    < / b l o c k >

    < b l o ck t y p e = " c or e / t e x t _ li s t " n a me = " c o n t e n t " / >

    < / b l o c k >

    Lots of new and interesting things to discuss here. The first thing youll noticeis that weve added some sub-nodes to our parent block, as well as introduceda new attribute named template.

    < b l o c k t y p e = " n o f r il l s _ b oo k l a y o ut / t e m p l a t e " n a m e = " r oo t "

    t e m p l a t e = " s i m p l e - p a g e / 2 c o l . p h t m l " o u t p u t = " t o H t m l " >.. .

    < / b l o c k >

    Youll remember that a nofrills booklayout/templateblock is our version of Ma-gentos core/template block. When your block is a template block, you can specifywhich template it should use in the template attribute

    t e m p l a t e = " s i m p l e - p a g e / 2 c o l . p h t m l "

    When you nest blocks in a Page Layout XML tree, its the equivalent of using theinsert method when youre creating them programmatically. The node structureof the XML mirrors the parent/child relationships you were previously settingup programmatically.

    Depending on how well youre following along (and if youve taken a few days offto digest everything and/or drink heavily), you may be wondering why its onlythe top level node that has a outputattribute. How does Magento know how torender the sub-blocks? The answer, of course, is in your simple-page/2col.phtmltemplate.

    F i l e : a p p / c o d e / l o c a l / N o f r i l l s / B o o k l a y o u t / d e s i g n / s i m p l e - p a g e / 2 c o l . p h t m l

    < ! D O CT Y P E h t ml >

    < h t m l >

    < h e a d >

    < m e t a c h a r s e t = " u tf - 8 " / >

    < t i t l e > < / t i t le >

    < ? p hp e c ho $ t hi s - > g e t C h i l d h tm l ( a d d i t i o n a l_ h e a d ) ; ? >

    < / h e a d >

    < b o d y >< ? p hp e c ho $ t hi s - > g e t C h i l d h tm l ( s i d e b a r ); ? >

    < ? p hp e c ho $ t hi s - > g e t C h i l d h tm l ( c o n t e n t ); ? >

    < / b o d y >

    < / h t m l >

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    37

  • 8/10/2019 No Frills Magento Layout

    39/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    The phtml template files dont care how their parent blocks have been instanti-ated, theyll function the same regardless of whether theyve been created with

    PHP code or XML code. The simple-page/2col.phtmltemplate is still looking fora child block named (in this example)additional head. Thats why its importantthat all your sub block elements have names

    n a m e = " a d d i t i o n a l _ h e a d "

    n a m e = " s i d e b a r "

    n a m e = " c o n t e n t "

    2.5 Action Methods

    Another new node is the node. Lets take a look at the sidebar block

    < b l o c k t y p e = " n o f r il l s _ b oo k l a y o ut / t e m p l a t e " n a m e = " s i de b a r " >

    < a c t i on m e t ho d = " s e t T e m pl a t e " >simple -page/sidebar.phtml

    < / b l o c k >

    Here youll see were still using a template block, but weve left off the templateattribute. Instead, weve added a sub-node named .

    An node will allow you to call methods on the block which containsit. The above node is equivalent to the following PHP code

    $ l a yo u t = M a ge : : g e t S i n g l et o n ( c o r e / l a yo u t ) ;

    $ b l o c k = $ l a y o ut - > c r e a t e B l o c k ( n o f r i l l s _ b o o k l a y o u t / t e m p l a t e , s i d e b a r ) ;

    $ b l o c k - > s e t T e m p l a t e ( s i m p l e - p a g e / s i d e b a r . p h t m l ) ;

    You can call anypublic method on a block this way, although some methodswont have any meaning when called from XML. Here weve used it as an alter-nate method of setting a template, but the Magento core themes are filled withother practical examples. Consider thepage/html head blocks (Mage Core Block Html Head).They contain a number of methods for adding CSS and Javascript files to yourpage

    < a c t i o n m e t h o d = " a d d C s s " > < s t y l e s h e e t > c s s / s t y l e s . c s s < / s t y l e s h e e t > < / a c t i o n >

    < a c t i o n m e t h o d = " a d d J s " > < s c r i p t > l i b / c c a r d . j s < / s c r i p t > < / a c t i o n >

    Well cover the node in greater depth later on in Chapter 5. You alsomay be interested in Appendix D, which contains a full list, in XML format, ofwhat actions may be called from what blocks.

    2.6 References and the Importance of text lists

    To review: Weve rendered out our blank page template again, but this timewith XML. Lets add some content to it. Edit your complexActionmethod so itmatches the following

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    38

  • 8/10/2019 No Frills Magento Layout

    40/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    p u b li c f u n c ti o n c o m p l ex A c t i on ( )

    {

    $ l a yo u t = M a g e : : g e t Si n g l e to n ( c o r e / l a y ou t ) ;$ p at h = M a ge : : g e tM o du l eD i r ( , N o f ri l ls _ Bo o k la y ou t ) . D S .

    p ag e - l a yo u ts . D S . c o mp l ex . x ml ;

    $ x m l = s i m p l e xm l _ l o a d_ f i l e ( $ p at h ,

    M a g e : : g e t C o n f i g ( ) - > g e t M o d e l C l a s s N a m e ( c o r e / l a y o u t _ e l e m e n t ) ) ;

    $ l a y o ut - > s e t X m l ( $ x m l ) ;

    $ t e xt = $ l a yo u t - > c r e a t e Bl o c k ( c o re / t e x t , f o xx y )

    - > s et T ex t ( " Th e q u ic k b ro w n f ox j u mp e d o ve r t he l az y d og . " );

    $ l a y o ut - > g e n e r a t e B l o c k s ( ) ;

    $ l a y o ut - > g e t B l o c k ( c o n t e n t ) - > i n s e r t ( $ t e x t ) ;

    e c h o $ l a y o ut - > s e t D i r e c t O u t p u t ( t r u e ) - > g e t O u t p u t ( ) ;

    }

    Just as we were able to in the previous chapter, we obtained a reference to thecontentblock, and inserted a new text block for the page. Its important to notethat we couldnt do this beforewed called generateBlocks. If we tried to, wedget an error along the lines of

    C a ll t o a m e mb e r f u nc t io n i n se r t () o n a n on - o b j ec t

    because we cant get a reference to a block before its been created. Reload thepage and youll see our new content, (see Figure 2.2)

    Figure 2.2

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    39

  • 8/10/2019 No Frills Magento Layout

    41/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    Of course, now were back to adding things to the layout via PHP. Wouldnt itbe nice if there was a way to get references to blocks via the Page Layout XML?

    As you might have guessed by our overtly rhetorical tone, The Page LayoutXML offers just such capabilities. At the top level of complex.xmladd the nodenamed below and give your page a refresh.

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / t e m p l a t e " n a m e = " r oo t "

    t e m p l a t e = " s i m p l e - p a g e / 2 c o l . p h t m l " o u t p u t = " t o H t m l " >

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / t e m p l a t e " n a me = " a d d i t i o n a l_ h e a d "

    t e m p l a t e = " s i m p l e - p a g e / h e a d . p h t m l " / >

    < b l o ck t y p e = " n o f ri l l s _ b oo k l a y o ut / t e m p l a t e " n a me = " s i d e b a r " >

    < a c t i on m e t h od = " s e t T e m p l at e " >

    simple -page /sid ebar. phtml

    < / b l o c k >

    < b l o ck t y p e = " c or e / t e x t _ li s t " n a me = " c o n t e n t " / >

    < / b l o c k >

    < r e f e r en c e n a m e = " c on t e n t " >

    < b l o ck t y p e = " c or e / t e x t " n a m e = " g o od b y e " >

    < a c t i on m e t h od = " s e t T e x t " >

    < te xt > T he l a zy d og w as o nl y f a ki n g i t . < / te xt >

    < / b l o c k >

    Voila! Another node added to content.

    The tag is the other tag thats valid at the top level of a PageLayout XML node. It allows you to get a reference to an existing,named node in the layout. Placing blocksinside the node is theequivalent of inserting them. So, the above Page Layout XML reference isequivalent to the following PHP

    $ la yo ut = M ag e :: g e tS in gl et on ( co re / l ay ou t );

    $ c on t en t = $l a yo ut - > g e tB l oc k ( c on t en t );

    $ te xt = $ la yo ut - > cr ea te Bl oc k ( c or e /t ex t , g oo db ye )

    - > s et T ex t ( T h e l a zy d og w as o n ly f a ki n g i t . ) ;

    $ c o n t e n t - > i n s e r t ( $ t e x t ) ;

    Nows a good time to remind you that its the core/text list node that makesthis insert/auto-render process work. If we were to get a reference to the toplevel root node and insert a block, that block wouldnt be rendered unless therootblocks template explicitly rendered it. A core/text listblock, on the otherhand, will automatically render any block inserted into it. This difference in

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    40

  • 8/10/2019 No Frills Magento Layout

    42/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    rendering between core/text listand core/template blocks is the biggest reasonfor head scratching layout problems Ive seen in the field.

    2.7 Layout Updates

    So, weve reached a waypoint in our journey to the depths of Magentos LayoutXML system. We now know how to create individual XML trees which canbe used to generate a page layout. However, it seems like weve swapped oneproblem for the another. Instead of having to worry about multiple PHP scriptsfor each page in our site, now we need to worry about multiple XML files. Wevemoved laterally, but havent made much progress on the core problem.

    And what good is that reference tag? It seems like itd be easier just to addcontent directly to the block structure.

    This brings us to the next piece of the Magento Layout puzzle: Layout Updates.

    2.8 Whats an Update

    Updates are fragments of XML that are added to a layout object one at a time.These fragments are then processed for special instructions and combined intoa Page Layout XML tree. The Page Layout XML tree (which we covered in thefirst half of this chapter) then renders the page.

    By allowing us to build Page Layouts using these chunks of XML, Magentoencourages splitting layouts up into logical components which can then be used

    to build a variety of pages. If that was a bit abstract and hard the follow, ourcode samples should clear things up.

    Well rely on our trusty hello world block to lead the way. Add the followingaction to our UpdateController.phpfile.

    # h t t p : / / m a g e n t o . e x a m p l e . c o m / n o f r i l l s _ b o o k l a y o u t / u p d a t e / h e l l o U p d a t e s

    p u b li c f u n c ti o n h e l l o U pd a t e s A ct i o n ( )

    {

    $ la yo ut = M ag e :: g et Si ng le to n ( co re / la yo ut );

    $ u p d a te _ m a n a ge r = $ l ay o ut - > g e t U p d at e ( ) ;

    $ u p d a t e _ m a n a g e r - > a d d U p d a t e ( < b l o c k

    t y p e = " n o f r i l l s _ b o o k l a y o u t / h e l l o w o r l d "

    n a m e = " r o o t "

    o u t p ut = " t o H t m l " / > ) ;

    $ l a y o ut - > g e n e r a t e X m l ( ) ;

    $ l a y o ut - > g e n e r a t e B l o c k s ( ) ;e c h o $ l a y o ut - > s e t D i r e c t O u t p u t ( t r u e ) - > g e t O u t p u t ( ) ;

    }

    Load the page, and youll once again see your hello world block.

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    41

  • 8/10/2019 No Frills Magento Layout

    43/164

    CHAPTER 2. XML PAGE LAYOUT FILES

    The three new lines were interested in above are

    $ u p d a te _ m a n a ge r = $ l ay o ut - > g e t U p d at e ( ) ;

    $ u p d a t e _ m a n a g e r - > a d d U p d a t e ( < b l o c k

    t y p e = " n o f r i l l s _ b o o k l a y o u t / h e l l o w o r l d "

    n a m e = " r o o t "

    o u t pu t = " t o H t ml " / > ) ;

    $ l a y o ut - > g e n e r a t e X m l ( ) ;

    These replace the manual loading of our page layout that we did above. First, aLayout object contains a reference to a Mage Core Model Layout Updateobject. Thisobject is responsible for managing and holding the individual XML chunks thatwere calling updates.

    2.8.1 Whats a Model

    You may be wondering why both the Layout and this new Update Managerobjects are models, even though they dont read/write to/from a database. Ifyouve used PHP based MVC systems in the past, youve probably becomeaccustomed to the idea that a Modelis an object that represents a table of datain a SQL database, or perhaps even multiple tables. While thats become onecommon understanding of the term, the original meaning of Model in MVC wasthe computer science term Domain Model.

    The Domain Model is an abstract concept. Its where you describe the conceptsand vocabulary of the problems youre trying to solve in code. Its sometimesreferred to as business logic, or the objects that you use when writing businesslogic code.

    The Un-Domain Model portions of a project are things like the code that runsyour controller dispatching, or the code that renders a template. This is codeyou might use on any projects for any number of companies, each with theirown Domain Model.

    Another way of thinking about this might be a school. Teachers, students,classes, which classes are in each room; these things are all the Domain Modelof a School. The non Domain Model would then be the school building itself,its plumbing and boiler, etc.

    We mention this here because much of the Magento model layer can be thoughtof in the more recent, Models are data in a database way. The layout andupdate hierarchy, however, cannot. A layout and an update object are bothmodels in the Domain Model sense of the word. They are modeling the busi-

    ness rules of creating HTML pages. This can be particularly confusing withthe update object, as a single update object will be used to manage multipleLayout Update XML fragments. Thats why were calling this object an UpdateManager

    $ u p d a te _ m a n a ge r = $ l ay o ut - > g e t U p d at e ( ) ;

    Prepared for Compaa Peruana de E-commerce S.A.; Copyright c2011 PulseStorm LLC

    42

  • 8/10/2019 No Frills Magento Layout

    44/164

    CHAPTER 2. XML PAGE LAYOUT FILES