Magento-The Basics

The Basics

Exam proportion: 6%.

Fundamentals

Magento uses Object Oriented Programming (OOP) as its programming paradigm which consists of classes, objects and methods. It also uses the Model-View-Controller (MVC) design pattern.

Magento makes use of an Event Driven Architecture (EDA). This is where components of the system are either producers or consumers of events. An EDA allows for loosely coupled, distributed software modules and is, by its nature, a reactionary system that performs actions based on stimuli.

Design Patterns

There are numerous development designs patterns used in Magento (Source).

Join with 20M+ community If you are also interested to make money online and want to know about more business ideas.

By subscribing you agree to our terms & conditions

Design Patterns Found In Magento in details

  1. Model View Controller Pattern

Model View Controller, MVC for short, is a design pattern where business, presentation and coupling logic are separated. Magento heavily utilizes XML as templating-logic and HTML mixed with PHP files for its views. Models are backed by Varien’s ORM. Most business logic happens in the models whereas the controllers map the model-data to the views.

Because Magento its views are “fat” – they often contain a lot of logic – its not rare that views have an additional PHP class (the Block system) which will help with rendering.

  1. Front Controller Pattern

The front controller pattern makes sure that there is one and only one point of entry. All requests are investigated, routed to the designated controller and then processed accordingly to the specification. The front controller is responsible of initializing the environment and routing requests to designated controllers.

Magento has only one point of entry (index.php) which will initialize the application environment (Mage::app()) and route the request to the correct controller.

  1. Factory Pattern

As implied by the name, the factory pattern is responsible of factorizing (instantiating) classes. It’s widely used through the Magento code base and leverages the autoloading system in Magento. By defining an alias in a module its config.xml you are letting the factory know where it can find classes.

There are various factory-helper methods in the Mage core class and one of them is getModel(). It accepts an alias for a class and will then return an instance of it. Instead of having include calls scattered through the code base, the factory pattern will instantiate classes in an uniform way.

  1. Singleton Pattern

Another way to retrieve an instance of a class, is to call Mage::getSingleton(). It accepts a class alias and before returning an instance, it checks the internal registry whether this class has already been instantiated before – this results in a shared instance. An example of where this is mandatory, is the session storage which should be shared through the code base instead of creating it anew every time.

  1. Registry Pattern

All the singletons are stored in the internal registry: a global scoped container for storing data. It is not only for internal use. The Mage::register($key, $value), ::registry($key) and ::unregister($key) methods can be respectively used for storing, retrieving and removing data from the registry. The registry is often used for transferring data between scopes when they cannot be passed on, otherwise.

  1. Prototype Pattern

Where the factory pattern (#3 on our list) stops, is where the prototype pattern continues. It defines that instances of classes can retrieve a specific other class instance depending on its parent class (the prototype). A notable example is the Mage_Catalog_Model_Product class which has a getTypeInstance method to retrieve the specific Mage_Catalog_Model_Product_Type with a specific subset of methods and properties not applicable to all products.

For example, the Mage_Downloadable_Model_Product_Type ultimately extends the Mage_Catalog_Model_Product_Type. If you are iterating over an order and want to call a specific method of a downloadable product, you will need to factorize it first with the getTypeInstance method of the original product.

  1. Object Pool Pattern

The object pool pattern is simply a box with objects so that they do not have to be allocated and destroyed over and over again. It’s not used a lot in Magento other than for heavy tasks where resources can get limited soon, like importing products. The object pool (managed by Varien_Object_Cache) can be accessed with Mage::objects().

  1. Iterator Pattern

The iterator pattern defines that there is a shared way to iterate over a container with objects. In Magento, this is handled by the Varien_Data_Collection which on its turn uses various baked-in PHP classes (like ArrayIterator) for having a more OO-interface to arrays. This ensures that model-collections will always have a common API to iterate over without being dependent of the actual models.

  1. Lazy Loading Pattern

Lazy loading ensures that loading data is delayed until the point when it is actually needed. This results in less resources being used. One of the lazy loading behaviors of Magento is that of collections. If you were to retrieve a collection of products with Mage::getModel(‘catalog/product’)->getCollection(), the database will only be touched when you actually access the collection by, for example, iterating over it or retrieving the count of models found.

  1. Service Locator Pattern

The service locator pattern abstracts away the retrieval of a certain service. This allows for changing the service without breaking anything (as it adheres to its abstract foundation) but also fetching the service as seen fit for its purpose.

Ryan exemplifies this with database connections. Another example is that of Magento its caching mechanism where Mage::getCache() is a service locator by-proxy for the cache storage supplied by Zend or other vendors.

  1. Module Pattern

Anyone familiar with Magento development has stumbled upon the module pattern. It basically defines that different domains are grouped into separate modules which function independent of each other and can be plugged-in to the main system as deemed appropriate. In an ideal situation, an implementation of the module pattern would make sure that each element can be removed or swapped. One of the protagonists of the module pattern in PHP is the Composer package manager.

Though Magento heavily relies on a modular architecture, its not modular to the bone. Certain functionality is heavily tied to the core and can not be easily changed. There is also the heavy usage of the super-global Mage core-class which introduces all sorts of system-wide dependencies not easily overseen.

  1. Observer Pattern

Magento its event-driven architecture is a result of an implementation of the observer pattern. By defining observers (or listeners), extra code can be hooked which will be called upon as the observed event fires. Magento uses its XML-data storage to define observers. If an event is fired with Mage::dispatchEvent($eventName, $data), the data storage will be consulted and the appropriate observers for $event will be fired.

  • Factory

  • Singleton

  • Registry

  • Event/Observer

  • Prototype

  • Object Pool

  • Iterator

  • View Helper

Constructors

Magento uses public __construct methods and, typically, protected _construct methods for class initialisation. More information on the difference between the two can be found on stackoverflow.

Arguments can be passed to models created through factories by using a second argument, e.g.

The argument parameter to getModel will be passed as is. There is no way to specify more than one argument for the constructor. To get around this restriction, we use an array.

High-Level Architecture

Code Pools

Magento is split up into three code pools.

  • Core
    • Contains core modules developed by Magento.
  • Community
    • The location of third party modules (extensions) that are packaged and released.
  • Local
    • Installation specific modules, customisations and overrides.

Typical Module Structure

  • Module Declaration

app/etc/modules/{namespace}_{module name}.xml

Defines the module, the code pool it is in, any dependencies and whether it is enabled.

  • Module Code

app/code/{codepool}/{namespace}/{module name}

Contains the module configuration and code. This includes:

  • Blocks
    • Block/
  • Controllers
    • controllers/
  • Configuration files
    • etc/
  • Models
    • Model/
  • Resource Models
    • Model/Resource/
  • Helpers
    • Helper/
  • Database Installation and Upgrade Scripts
    • sql/
  • Data scripts
    • data/

Magento Templates and Layout Files

app/design/{area}/{package}/{theme}/

Layout and template files are organised into folders by store area, package (theme namespace) and theme. Inside, the layout files and template files are separated into layout/ and template/ directories respectively.

Magento Skin and JavaScript files location

skin/{area}/{package}/{theme}

As with template files, most Magento assets (js, css and images) are organised by store area, package and theme. Inside, the convention is to put different types of assets into their own folders, but it is not enforced.

js/

Contains theme independent JavaScript files and other assets (e.g. css, images), organised by library.

Magento Design Areas

  • Adminhtml
    • Contains the files dealing with the presentation of the Magento backend.
  • Frontend
    • Contains the layouts, templates and assets for the customer facing areas of Magento.

Class Naming Conventions and Autoloader

Magento’s include path is set to look for files (app/code) and libraries (lib/) in each of the code pools (core, community and local). Classes are resolved using the PSR-0 autoloading standard. That is, the autoloader simply replaces the underscores in the class name with directory separators and adds the .php extension:

The class naming convention for most Magento classes is:

Module Conflict Resolution

Conflicts can arise in three ways:

  • Configuration conflicts
    • Two modules could be extending the same class or making configuration changes in the same areas. You can specify precedence explicitly with a <depends> dependency tag in the module declaration; forcing one module to always be loaded before the other.
  • Rewrite conflicts
    • Magento models and blocks can only be rewritten once in config.xml. But we can sequence rewrites (ensuring that both changes are applied) by extending the first rewrite within the second.
  • Theme conflicts
    • Changing the layout (moving, removing and replacing blocks, or changing their templates) can introduce conflicts if other modules are expecting a particular structure. Investigate the templates and module configuration to locate the causes and resolve them.

Magento Configuration

Config Load

Configuration in Magento is stored as an XML tree. Magento reads in the config.xml files for each module and merges the configuration into a single tree. This allows modules to modify existing configuration elements and add new ones.

Class Group Config and Factory Methods

In Magento models, blocks and helpers are registered in configuration using the following format:

module identifier (the part before the slash) to find the class name prefix to prepend to the object name (the part after the slash) to find the class that needs to be instantiated. This allows modules to redefine existing objects and functionality by changing the configuration.

Class Overrides

Object classes can be overridden in configuration using the following syntax:

This indicates to the factory methods that the specified class should be used instead of the usual class the object would resolve to.

Register an Observer

Observers are registered in Magento using the following syntax:

This requires specifying the area of the event listened to (frontend, adminhtml or global), the event being listened to, the observer identifier (unique name), the observer object type (e.g. singleton model), the class used and the method to call.

Function and use of automatically available events

Magento dispatches a number of events automatically that can be observed, e.g. *_save_before and *_load_after.

This provides us with the ability to modify models at the point before they are saved to the database or to modify a model immediately after its data has been retrieved from the database.

Cron Jobs

Crons jobs are defined in Magento using the following syntax:

The cron job schedule can either be a cron schedule expression (inside a tag) or a configuration path (inside a config_path tag) where the crons schedule expression is stored. The tag defines the function to execute in the format {grouped class name}::{method name}.

Loading active modules

Magento creates a central list of installed modules by loading all *.xml files within app/etc/modules. It records whether they are active and the location of their full configuration ().

Common config load methods

  • Mage::app()->getConfig()->getNode();
  • Mage::getStoreConfig();
  • Mage::getStoreConfigFlag();

Per-Store Configuration in XML DOM

Per-store configuration values are located in the stores->{store name} part of the configuration and are usually retrieved with the Mage::getStoreConfig() method.

Configured Class prefixes

Prefixes are used for blocks, models and helpers. Using prefixes and not referring to classes directly by name allows rewriting the classes in the configuration and without the need to modify the code that uses them.

Internationalisation

Store views are typically used for internationalisation in Magento, with each one being configured for a particular language.

In template files $this->__(‘Translate Me’) method is used to manage translatable text. This is then handled by Mage_Core_Helper_Data and Mage_Core_Model_Translate.

Before outputting this string it is checked against a number of locations. The priority for translations are in this order:

  1. Inline
    • The core_translate database table
  2. Theme
    • app/design/$area/$package/$theme/locale/
  3. Module
    • app/locale/

If developer mode is enabled, Magento doesn’t use translations unrelated to module.

Module scope translation:

Sub-domains and Sub-directory Setup

To make use of the internationalisation, a store view with appropriate configurations should be initialised. Two ways that this can be handled is by sub-domain e.g. fr.example.com and sub-directory, e.g. example.com/fr.

There are advantages and disadvantages of each. But in general, sub-domains and sub-directories achieve the same effect.

Sub-domains are slightly easier for linking content. Another advantage of sub-domains is that they can be hosted on separate servers. This can be ideal for geo-locating boxes by country or region according to the language served per store view.

With sub-directories, we strengthen name-recognition for the primary domain. And enjoy the benefit that all store views are contributing to SEO efforts by raising total hits for the store brand. But we sacrifice the opportunity for cleaner URLs with localized domain branding. (e.g., http://amazon.com and http://amazon.de vs. http://amazon.com and http://amazon.com/germany).

Prashant Rawal

I’m a freelance full-stack web developer having over 8 years of experience in Wordpress development. I am also Blogger and Affiliate Manager to help people starting their money making blogs using larget affiliate networks.

Leave a Reply

Back to top
powered by proof factor - increase conversions with social proof notifications
Share via
Copy link
Powered by Social Snap