You are on page 1of 9

Magento Custom Module Development

Magento custom module development is a core part of any Magento development or Magento project, because
at any stage you may want to integrate your own functionality/module in your existing Magento project. 

Throughout this series, I'm referring Magento Community Edition 1.7, though custom module structures are the
same in all versions of Magento. Before going we're going to start actual module development, let's quickly
understand the basic structure of Magento.  Magento directory structure:

Introduction to Magento
MVC Structure
Like any other major frameworks such as
Joomla, CakePHP, CodeIgniter, etc.,
Magento also follows the MVC-based
architecture though this is little bit
different than core PHP MVC architecture.
Here, I'll explain the difference in
Magento architecture by comparing it with
simple PHP MVC architecture.

PHP MVC architecture

In the typical MVC pattern, the flow of the


application is something like this:

1. There is main entry point -


index.php - from where the entire
app routing mechanism is
determined.
2. Based on this routing mechanism
and requested URL pattern, the app
will call the appropriate controller.
3. The controller then calls the
appropriate views.
4. Finally, the view files collect the
data from model files and display the data.

Magento MVC architecture


Magento's MVC architecture adds a few layers to the MVC pattern, but the basic flow of control of an
application is like this:

1. There is main entry point - index.php - from where the whole app will be initialized.
2. Base on the requested URL appropriate controller will be called. 
3. Controller defines the pages and load the layout files for those pages.
4. Layout files tells the controllers which block files to use.
5. Block files collect the data from models and helpers files and pass it to templates files.
6. Templates files receive data and render html.
Initially, this may be difficult to understand since it contains a few extra layers. To get more familiar with the
flow of control, let's develop a custom "Hello World" module.

Before Starting With Modules


 I am assuming that you already have a working copy of Magento with version 1.7 or 1.7+ (or else as
version does not matter at this stage)
 Disable the cache. To Disable the cache Go to Magento Admin Panel  > System > Cache
Management  > Select all cache type from left side checkboxes > Select Action: disable from right top
drop down > click Submit.

The Structure of a Magento Module


Code Pools

Magento contains three type of code pools where the all custom and core modules of Magento are resides. 

1. Core pools contain all the core modules which are by default comes with a Magento installation. These
modules are written by Magento developers. It's recommended not to modify these modules because
whenever you will upgrade your Magento installation, all the core modules will be overwritten and your
modifications will be lost.
2. Community pools contain all the modules - that is, custom modules - that are developed by third-party
programmers to be installed through Magento Connect. These modules generally extend core modules
and offer their own functionality that can often be used anywhere in Magento.
3. Local pools contain all the custom module that are going to be used for a particular project but are not
readled in Magento Connect

Thus, we have two choice of pools: Community or Local. Since we are working on our own project, we are
going to use a local pool, though there's no restriction on using the community pool, either.

Structure

Magento modules consist of the following components:

 Blocks contain functions that are used to display data in templates.


 Models contain the business logic of modules.
 Resource Models contains functions that are used for database interaction.
 Controllers defines page layout and blocks files and are loaded when a URL is requested.
 etc contains configuration files in XML formats which tells Magento how many files modules have and
how the module interacts.
 Helpers contain functions that are used for defining common business logic (such as image resize,
validation). These functions can used anywhere across the Magento application
 sql contains SQL scripts to create, modify, or delete SQL tables.

Module Naming
We need to give a name to our module. Generally, Magento module names are made of two
parts: <Namespace>_<Module>. The best practice to give a Magento module a name is choose <Namespace>
as an author or a company name and <Module> as a actual module name.

Based on these naming convention, I am giving our module the Chiragdodia_Mymodule name. We will
reference this name throughout this series.

Code Set Up and Configuration

 Lets create the directories base on above structure. Go to your Magento installation direction then navigate
to app/code/local  and create the directories as shown below.

Next, we will configure and activate our module by creating config file Chiragdodia_Mymodule.xml in
the app/etc/modules directory. This directory contains config files for all modules.

1
2<?xml version="1.0"?>
<config>
3    <modules>
4        <Chiragdodia_Mymodule>
5        <active>true</active>
6        <codePool>local</codePool>
        </Chiragdodia_Mymodule>
7    </modules>
8</config>
9

This file will tell Magento about the location of our module. In the active tag, we have specified true to
enable our module. If everything is correct thus far, then you will find your module in the Magento Admin
Panel   > System > Configuration > Advanced > Advanced  > Disable Modules Output list. From here you can
enable and disable your module.

Getting Started: Development


Next we will create our module configuration file. This file will tell Magento all about our module. This
includes how many files our module contains, what type of files (models, helpers, database classes), and so on.

Go to app/code/local/Chiragdodia/Mymodule/etc and create a config.xml  file that will contain following


content

<?xml version="1.0"?>
<config>
    <modules>
        <Chiragdodia_Mymodule>
            <version>0.1.0</version>    <!-- Version number of your module -->
        </Chiragdodia_Mymodule>
    </modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>Chiragdodia_Mymodule</module>
                    <frontName>mymodule</frontName>
                </args>
            </mymodule>
        </routers>
    </frontend>
</config>

Let's go through line by line to understand each tag. Here, the first tag is <module> that contains the name and
version of our module. The version number is very important when it comes to updating your module update
your module.

The <frontend> tag will tell Magento about the controller dispatched. Inside the <frontend> tag, we have
defined <routers> that tells Magento how to access our controllers via the routing mechanism. 

In the <mymodule> tag, we have defined module name in <module> tag and frontend name in <frontName>. By
using a frontend name, we can access our module in frontend
like yoursitename.com/index.php/mymodule/index.

By calling yoursitename.com/index.php/mymodule
or yoursitename.com/index.php/mymodule/index Magento will look for index action of your module's
controller file. As such, we need to create our controller file.

Go to  app/code/local/Chiragdodia/Mymodule/controllers and create file IndexController.php with


following content.

Note that each file's name and class names are case sensitive in Magento It's very important that you are taking
care in naming your work when creating files and classes.

1
<?php
2class Chiragdodia_Mymodule_IndexController extends Mage_Core_Controller_Front_Action
3{
4    public function indexAction()
5    {
6        echo "Hello tuts+ World";
    }
7}
8

Now open URL yoursite.com/index.php/mymodule/index it will print "Hello tuts+ World". Awesome -


we're finally done with our first hello world module.

Controller Dispatch

Here we have extend the class Mage_Core_Controller_Front_Action that contains all the methods which are
using in routing of url. The Magento class name reflects the location of class file. So the
class Mage_Core_Controller_Front_Action resides in location Mage > Core > Controller > Front >
Action.php

See the class name of our controller that is Chiragdodia_Mymodule_IndexController. Magento controller to
be named in such a way that it reflects (<module>tag)_(Action Controllername)(keyword Controller).

 <module>tag = Chiragdodia_Mymodule (we have defined this tag in config.xml)


 Action Controllername = Index
 Action controller followed by the Controller keyword 

Based on this pattern, the name of our controller is Chiragdodia_Mymodule_IndexController

Now see the URL pattern which is follow the below route pattern
yoursite.com/index.php/frontendname/actionControllername/actionmethod

 frontendname = mymodule
 actionControllername = Index
 actionmethodname = Index

Based on this URL pattern, our module's URL is yoursite.com/index.php/mymodule/index/index. You


can also access it using yoursite.com/index.php/mymodule because whenever you have not specified
an actionController or actionmethod name, Magento loads the index controller and index action by default.

Overview
A Magento module is a logical group of components that encapsulates a particular business function, typically a
business task. All components of a module relate to the module’s specific function. For example, each element
of the Shipping module contains all the code and interfaces needed to implement core shipping-related tasks. A
module directory typically contains blocks, controllers, helpers, models, configuration files, and other
components that contribute to the module’s core purpose.

Module structure is defined by both module code components and logical structure.

Module components
All types of modules contain the following core elements, categorized by directory:

 /block

 /controllers

 /etc

 /helper

 /model

 /sql

Block

Blocks help provide the data used in the View component of the module structure. Blocks coordinate models
with the template files. The files in this folder load the data from database and transfer it to the templates in
your theme (PHTML files).

Controllers
Controllers represent all business logic actions for the given request. These actions include dispatch(),
preDispatch(), postDispatch() methods and delegate commands to other parts of the system. Controllers
correspond to the Controller portion of the Model-View-Controller model.

/etc

This directory contains the XML files that declare and configure behavior of all modules. Each module must
have a config.xml file, where all models, routers, blocks, helpers are declared.

Optionally, this folder could have adminhtml.xml (grant permissions for your tabs/sections in server-side
menus) and system.xml (creates this new section or specifies where it should be displayed in the existing one).

Magento 2.x looks for configuration information for each module in that module’s ‘/etc’ directory. Depending
on the purpose of your module, it might contain the following configuration files in its /etc directory:

 acl.xml

 config.xml

 di.xml

 module.xml

 webapi.xml

Configuration files that are in the top level of that module’s /etc directory are global to that component.
Configuration files placed in subdirectories (adminhtml, frontend, webapi_rest, webapi_soap) apply only to
those respective functional areas.

The specific set of configuration files that your module requires depends on the module’s purpose and the
Magento area in which it functions.

Helper

Helpers contain utility methods, which are commonly used throughout the application. Methods, as declared in
helpers, can be called from any template file or block, model, controller class.

Each module has a default Data Helper class Modulename/Helper/Data.php.

Model

In a typical Model-View-Controller-based application, models are used to connect to the database and process
data from and to it. Magento has adapted this pattern slightly.

Resource Models are objects that contain code that fetches data from a data store. In practice, this means a
resource model is the object that contains the SQL building and fetching code, as well as references to objects
that connect to the main Magento database.
Models are objects that contain database-agnostic code for interacting with a type of data. In traditional data
modeling terms, your model objects contain the business logic for a particular type of object (types include
Product and Customer).

A Magento model object contains a reference to a resource model, which it uses to load its data. There’s an
individual resource model object for each model object. For example, a Product Model has a Product resource
model.

sql

Structures in this directory handle any custom database tables that are used by the module and process all
upgrades to the extension.

The main difference between models, resources and collections is described as follows:

1. Model: these classes are used to representing a single item normally from the
database,
2. Resource: these classes are used to fetch and save data for an item to the database,
3. Collection: these classes are used to deal with more than one item from the
database,

Magento Model :
Magento Model is handle all logical operation with database.Its ActiveRecord-like/one-object-one-table
Model, and there’s also an Entity Attribute Value (EAV) Model. Each Model also gets a Model Collection. .

Magento Resource Model


Magento’s resource simply connect with the database and performs the CRUD operations. Actually they
manage the different reading/writing connections.Its another layer between model and database when you
interacting with database.

Magento Collection Model:


Collection referees the collection of models.it contains many models.When we want results based on different
model then we need to create collection or we can use existing collection.
It gives us a whole load of convenience methods, making it easier to manipulate lists of entities and reducing
the need to write complex sql.

Architectural diagrams 2.0


Magento architecture from different perspectives
Depending upon your role and purpose for learning more about Magento, there are several different ways to
view the Magento architecture. For example, a developer who wants to create new modules or perhaps
customize an existing module will want to understand the architecture of a module itself, and how it fits into the
larger view, with the Magento framework and other components. However, a merchant who wants to quickly
build an online store front wants to view the collection of components from a higher level, and understand the
components that impact the look, feel, and user interaction components.

Architecture layers diagram


The following diagram illustrates the components of Magento, and shows the “layers” or tiers, for all
components, as well as the Magento framework, 3rd party libraries, the supported database, and other
technologies.

There are different kind of indexes in Magento.


All of the indexers are there to make things run faster.
I will cover here only a few of them.

Flat Index
There are 2 such indexes. One for categories and one for products.
By default the category and product entities (and customers and customer addresses but they are not important
in this situation) are EAV entities. This is very nice for extensibility. But it's a performance killer because in
order to get all values for all the attributes you need a lot of joins or multiple queries.
Here is where the flat indexer comes into play.
It transforms the EAV structure into a flat structure. I mean it creates a table (one for each store view in
Magento) that has one column corresponding to an attribute. This makes selects faster. For categories all
attributes are converted to table columns. For products only the ones you mark as 'Used in product listing'
because you can sell all types of products with different attributes and creating one table with a gazillion
columns may not be possible.
Also, some products may be disabled or may not belong to a certain website and there is no need to include
them in the entries to search. They are excluded by the indexer.
The generated flat tables are used for reading data in the fronend. The backend still uses the EAV structure.

Catalog Search Index


You can search for products by many attribute values. Some of them may not be included in the flat tables
generated by the flat indexer. This index fills in a table with the searchable attribute values for products so it's
easier to look for them based on keywords. Having all the info in one table (or one field) makes it possible to
use Full text search and get relevant results.

Product Prices.
The price of a product can be affected by many variables. For example, customer group, website, catalog
discount rules.
Same as above, getting the products with their prices will mean a lot of joins or multiple selects. IN addition
bundle products have a strange pricing system. This indexer aggregates the data in some tables
(catalog_product_index_price_*) and makes the selects (sorting and filtering) much easier.

Catalog url Rewrites


This cleans up the url rewrite rules by setting which url corresponds to which product or category. It's easier this
way for the url management internal system to decide which page should you view when calling a non-standard
url. Instead of searching through all the product and categories URL keys it just searches in one table.

Category Products
In Magento you can set a category attribute named 'Is Anchor' to true or false. If it's true it means that the
category in question will list all the products from it's child categories. Again, determining this realtime it will
take more resources than just reading one table. This indexer creates the association between products and
categories based on the associations you set in the backend and the 'Is Anchor' flag on the categories.

Stock Status
For simple products it's easy. They can be in stock or out of stock, but for configurable, grouped and bundle is
not that easy. They can be in stock or out of stock depending on the child products associated to the main
product. Again (I'm just repeating my self here) getting their status real time would mean a lot of queries.

Product Attributes.
This one collects all attributes that can be used in the layered navigation for same reason. Having all of them in
one place for faster reading.

Tag Aggregation
I have no idea what this does. I've never used tags in a real live project.

You might also like