Ans. Magento is a feature-rich eCommerce platform built on open-source technology that provides online merchants with unprecedented flexibility and control over the look, content and functionality of their eCommerce store. Magentos intuitive administration interface features powerful marketing, search engine optimization and catalog-management tools to give merchants the power to create sites that are tailored to their unique business needs. Designed to be completely scalable and backed by Variens support network, Magento offers companies the ultimate eCommerce solution.

Q 2. What is the difference between Mage::getSingletone() andMage::getModel() in Magento

Ans. Mage::getSingletone() always finds for an existing object if not then create that a newobject but Mage::getModel() always creates a new object.

Q 3. Why Magento use EAV database model ?

Ans. In EAV database model, data are stored in different smaller tables rather than storing in asingle table.product name is stored in catalog_product_entity_varchar tableproduct id is stored in catalog_product_entity_int tableproduct price is stored in catalog_product_entity_decimal tableMagento Use EAV database model for easy upgrade and development as this model givesmore flexibility to play with data and attributes.

Q 4. How to upgrade to the latest version using Magento Connect?

Ans. Upgrading Magento to the latest version is a fairly simple task. Copy and Paste this key magento-core/Mage_All_Latest VIA Magento Connect where it states Paste extension key to install:. This will upgrade Magento to the newest version.

Q 5. Explain about the Modules of Magento?

Ans. Magento supports installation of modules through a web-based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.

There are three categories of modules hosted on Magento Connect:

  • Core Modules
  • Community Modules
  • Commercial Modules

Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.

Q 6. What technology used by Magento?

Ans. Magento uses PHP as a web server scripting language and the MySQL Database. The data model is based on the Entity-attribute-value model that stores data objects in tree structures, thus allowing a change to a data structure without changing the database definition.

Q 7. What is MVC structure in Magento?

Ans. The Model-View-Controller (MVC) architecture traces its origins back to the Smalltalk Programming language and Xerox Parc. Since then, there have been many systems that describe their architecture as MVC. Each system is slightly different, but all have the goal of separating data access, business logic, and user-interface code from one another.

Q 8. What is benefit of namespace (package) in magento?

Ans. We can have more than one module with same name but they should be placed in different namespaces. All magento core modules are contained in mage namespace.

core/Mage/Catalog

and all custom modules are placed in

local/CustomModule

Q 9. How to include CMS block in template file(.phtml)?

Ans. Access block’s content from .phtml template file by :


<?php  echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘static_block_id’)->toHTML(); ?>

Q 10. How to add an external javascript/css file to Magento?

Ans.

css/yourstyle.css

or

skin_jsjs/ yourfile.js

skin_csscss/yourstyle. css

Q 11. What are handles in magento (layout)?

Ans. Handles are basically used for controlling the structure of the page like which block will be displayed and where. First level child elements of the node are called layout handles. Every page request can have several unique Handles. The handle is called for every page. handle for products belongs to virtual product type, PRODUCT_TYPE_simple is called for product details page of simple product type and PRODUCT_TYPE_virtual is called for the virtual product detail page and customer_logged_in handle is called only if customer is logged in. The muster_index_index handle is created by combining the frontName (muster), Action Controller (index), and Action Controller Action Method (index) into a single string and this handle will be called only when /zag/index/index url is accessed.

Q 12. What is in magento?

Ans. The routers tag allow us to decide frontname for each module. The tag is defined in config.xml file of module. For Namespace_MyModule frontname is moduleurl so the url will be like :

websiteurl.com/moduleurl/controllername/actionname

standard

Namespace_MyModule

moduleurl

Q 13. Which factors affect performance of magento?

Ans.

1. EAV structure of magento database, even for retrieving single entity the query becomes very complex .

2. Magento’s template system involves a lot of recursive rendering

3. Huge XML trees built up for layout configuration, application configuration settings

 

Q 14. How to improve magento performance?

Ans.

Enabled magento caching

MySQL Query caching

Enable Gzip Compression

Disable any unused modules

Disable the Magento log

Optimise your images

Combine external CSS/JS into one file

Enable Apache KeepAlives: Make sure your Apache configuration has KeepAlives enabled.

Q 15. How to get the Total Price of items currently in the Cart?

helper(‘checkout’)->formatPrice(Mage::getSingleton(‘checkout/cart’)->getQuote()->getGrandTotal()); ?>

Q 16. How to set different themes for logged in users?

if(Mage::getSingleton(‘customer/session’)->isLoggedIn()):

Mage::getDesign()->setPackageName(‘package_name’)->setTheme(‘themename’);
endif;

Q 17. How to create magento custom module?

Ans. Steps to create custom magento module:

Namespace : Zag

Module Name : Mymodule

1. Create directory Mymodule in app/code/local/Zag

2. Create Block, controllers, etc, Module directories. Create controller, block and module file as required.

3. Create module configuration file (app/code/local/Zag/Mymodule/etc/config.xml).

4. Create xml file (app/etc/modules/Zag_ Mymodule.xml)to enable/disable module and tell magento system from which code pool that module will be taken.

Q 18. How to set different themes for each store?

Ans. Go to : System>Designs

Then, add new design change or edit existing. You can select Store and Custom Design.

Q 19. How to make product’s custom attribute searchable in adavance search?

Ans. Go to : Catalog > Attribues > Manage Attribues

Edit the attribute and select “Yes” for Use in Advanced Search.

Q 20. How to fetch 5 bestsellers products programmatically?

Ans.


Mage::getResourceModel(‘reports/product_collection’)

->addOrderedQty()

->addAttributeToSelect(‘*’)

->setPage(1, 5)

->load();

 21-Explain Magento’s MVC architecture

Ans. First of all, what is MVC?

MVC stands for Model-View-Controller. Any application that separates it’s data access, business logicand user interface is called MVC. There can be two types of MVC: convention-based andconfiguration-based. Example, cakePHP is convention-based, i.e. you just need to follow the instructions of the core system to get your module ready in just few lines. Magento is configuration-based, i.e. you need to specify each and every thing to your module’s config file in order to get it work. Magento has Controller (for Routing), Block (for Business Logic), Model (for DB access, sql) and Template file (for Presentation i.e. View).

How Magento’s MVC works:

1. When you enter the URL (something like http://mysite.com/frontname/controller/method/param1/value1/param2/value2), this URL is intercepted by one PHP file called index.php which instantiates Magento application

2. Magento application instantiates Front Controller object

3. Further, front controller instantiates Router objects (specified in module’s config.xml, global tag)

4. Now, Router is responsible to “match” the frontname which is in our URL

5. If “match” is found, it sees controller name and method name in the URL, which is finally called.

6. Now depending on what is written in action name (method name), it is executed. If any models are called in it, the controller method will instantiate that model and call the method in it which is requested.

7. Then the controller action (method) instantiate the Layout object, which calls Block specified for this action (method) name (Each controller action name have block and template file associated with it, which can be found at app/design/frontend or adminhtml/namespace/module/layout/module.xml file, name of layout file (module.xml) can be found in config.xml of that module, in layout updates tag).

8. Template file (.phtml) now calls the corresponding block for any method request. So, if you write $this->methodName in .phtml file, it will check “methodName” in the block file which is associated in module.xml file.

9. Block contains PHP logic. It references Models for any data from DB.

10. If either Block, Template file or Controller need to get/set some data from/to database, they can call Model directly like Mage::getModel(‘modulename/modelname’).

For diagramatic view: click here (courtsey: Alan Storm)

22 =How Magento ORM works?

Ans. ORM stands for Object Relational Mapping. It’s a programming technique used to convert different types of data to Objects and vice versa.

In Magento, ORM is shown as Model (based on Zend Framework’s Zend_Db_Adapter), which further breaks down to two types of Models.

– First is the “simple” i.e. Regular Models which is nothing but flat table or our regular table structure.
– Second Model is EAV (Entity Attribute Value), which is quite complicated and expensive to query.

All Magento Models interacting with database are inherited from Mage_Core_Model_Abstract class, which is further inherited from Varien_Object.

Difference between two Models is, Simple Model is inherited from Mage_Core_Model_Resource_Db_Abstract class,
while EAV is inherited from Mage_Eav_Model_Entity_Abstract.

For those who don’t know what EAV is, please read my 3rd answer below.

So, to end up this question,
when you want to get some data in Magento, you call it like this:

Mage::getModel(‘module/model’)>load(1);

where 1 is the primary key id for some Regular/Simple table, while in EAV so many tables are joined to fetch just single row of data.

23. What is EAV in Magento?

Ans. EAV, stands for Entity Attribute Value, is a technique which allows you to add unlimited columns to your table virtually. Means, the fields which is represented in “column” way in a regular table, is represented in a “row” (records) way in EAV. In EAV, you have one table which holds all the “attribute” (table field names) data, and other tables which hold the “entity” (id or primary id) and value (value for that id) against each attribute.

In Magento, there is one table to hold attribute values called eav_attribute and 5-6 tables which holds entity and data in fully normalized form,

– eav_entity, eav_entity_int (for holding Integer values),
– eav_entity_varchar (for holding Varchar values),
– eav_entity_datetime (for holding Datetime values),
– eav_entity_decimal (for holding Decimal/float values),
– eav_entity_text (for holding text (mysql Text type) values).

EAV is expensive and should only be used when you are not sure about number of fields in a table which can vary in future. To just get one single record, Magento joins 4-5 tables to get data in EAV. But this doesn’t mean that EAV only has drawbacks. The main advantage of EAV is when you may want to add table field in future, when there are thousands or millions of records already present in your table. In regular table, if you add table field with these amount of data, it will screw up your table, as for each empty row also some bytes will be allocated as per data type you select. While in EAV, adding the table column will not affect the previously saved records (also the extra space will not get allocated!) and all the new records will seamlessly have data in these columns without any problem.

24. Difference between Mage::getSingleton() and Mage::getModel()

Ans. The difference between Mage:getSingleton() and Mage::getModel() is that the former one does not create an object if the object for same class is already created, while the later creates new objects every time for the class when it’s called.

Mage::getSingleton() uses the “singleton design pattern” of PHP. If the object is not created, it will create it.

Mage::getSingleton() is mostly used when you want to create an object once, modify it and later fetch from it. Popular example is session, you first create a session object, and then add/remove values from session across different pages, so that it retains your values (e.g. cart values, logged in customer details, etc.) and doesn’t create new session object losing your last changes.

Mage::getModel() is used when you want to have the fresh data from the database. Example is when you want to show records from database

25. What is codePool in Magento?

Ans. codePool is a tag which you have to specify when registering new module in app/etc/modules/Company_Module.xml
There are 3 codePools in Magento: core, community and local, which are resided at app/code/ directory.
Core codePool is used by Magento core team, Community is generally used by 3rd party extensions and Local codePool should be used for in-hour module development and overriding of core and community modules for custom requirement.
So in short, codePool helps Magento to locate module inside app/code/ for processing.

26. When will you need to clear cache to see the changes in Magento?

Ans. When you have added/modified XML, JS, CSS file(s).

27. How will you enable product’s custom attribute visibility in frontend?

Ans. n the Manage Attributes section of the custom attribute, select Visible on Product View Page on Front-end and Used in Product Listing to Yes.

28. Difference between EAV and flat model

Ans. EAV is entity attribute value database model, where data is fully in normalized form. Each column data value is stored in their respective data type table. Example, for a product, product ID is stored in catalog_product_entity_int table, product name in catalog_product_entity_varchar, product price in catalog_product_entity_decimal, product created date in catalog_product_entity_datetime and product description in catalog_product_entity_text table. EAV is complex as it joins 5-6 tables even if you want to get just one product’s details. Columns are called attributes in EAV.

Flat model uses just one table, so it’s not normalized and uses more database space. It clears the EAV overhead, but not good for dynamic requirements where you may have to add more columns in database table in future. It’s good when comes to performance, as it will only require one query to load whole product instead of joining 5-6 tables to get just one product’s details. Columns are called fields in flat model.

29. Is it mandatory to give Namespace while creating custom module in Magento?

Ans. No

30. Can you have more than one Grid in a module?

Ans. Yes

31. How many database tables will Magento create when you make a new EAV module?

Ans. Magento creates 6 tables when you create new EAV module. Tables: module, module_datetime, module_decimal, module_int, module_text and module_varchar. one is the main entity table, and rest 5 tables which holds attribute’s data in different data types. So that integer values will go to module_int table, price values to module_decimal, etc.

33. Where will you write your module’s business logic in Magento?

Ans. inside Model

34. Explain different types of sessions in Magento (e.g. customer/session, checkout/session, core/session) and the reason why you store data in different session types?

Ans. Customer sessions stores data related to customer, checkout session stores data related to quote and order. They are actuall under one session in an array. So firstname in customer/session will be $_SESSION[‘customer’][‘firstname’] and cart items count in checkout/session will be $_SESSION[‘checkout’][‘items_count’]. The reason Magento uses session types separately is because once the order gets placed, the checkout session data information should get flushed which can be easily done by just unsetting $_SESSION[‘checkout’] session variable. So that the session is not cleared, just session data containing checkout information is cleared and rest all the session types are still intact.

35. Magento: Design Patterns

Ans. Below is the list of magento design pattern Which Magento used

Factory:

It implement the concept of factories and deals with the problem of creating objects without specifying the exact class of object that will be created.
$product = Mage::getModel(‘catalog/product’);

Singleton:

It restricts the instantiation of a class to one object. It will refer to same object each time called.
$category = Mage::getSingleton(‘catalog/session’);

Registry:

It is a way to store information throughout your application.
Mage::register(‘key’,$value); //stores $currentCategory = Mage::registry(‘key’); //retrives

Mage::register(‘key’,$value); //stores
$currentCategory = Mage::registry(‘key’); //retrives

Prototype:

It determines the type of object to create. In Magento it can be Simple, Configurable, Grouped, Bundle, Downloadable or Virtual types.
Mage:getModel(‘catalog/product’)->getTypeInstance();

Observer:

It is mainly used to implement distributed event handling systems. Here the subject maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
Mage::dispatchEvent(‘event_name’, array(‘key’=>$value));







Class_Name
methodName





Object Pool:

It is used to reuse and share objects that are expensive to create.
$id = Mage::objects()->save($object);
$object = Mage::objects($id);

Iterator:

It is used to traverse a collection and access the collection’s items.
Mage::getModel(‘catalog/product’)->getCollection();

Lazy Loading:

It is used to defer initialization of an object until the point at which it is needed.
$collection_of_products = Mage::getModel(‘catalog/product’) ->getCollection();

Decorator:

It is used to extend or modify the behaviour of an object at runtime.
decorateTable(‘product_comparison’);

Helper:

Multiple methods are available for use by other objects. Here you can use core’s helper methods from anywhere in the application.
Mage::helper(‘core’);

Service Locator:

Allows overrides or renamed physical resources (e.g. Classes, DB tables, etc)
Mage::getModel(‘catalog/product’) and $installer->getTable(‘customer/address_entity’);

Null object
Provide an object as a surrogate for the lack of an object of a given type. / The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.

$collection->getFirstItem();

36.print vs echo

Ans. print has a return value of 1 so it can be used in expressions

whereas

echo has a void return type;

echo can take multiple parameters,

although such usage is rare; echo is slightly faster than print.

37.var_dump vs print_r

Ans. var_dump prints out a detailed dump of a variable,

including its type and the type of any sub-items (if it is an array or an object).

whereas

print_r prints a variable in a more human-readable form:

strings are not quoted, type information is omitted, array sizes aren’t given, etc.

var_dump is usually more useful than print_r when debugging.

It’s particularly useful when you don’t know exactly what values/types you have in your variables.

38. What is Magento’s Compilation feature?

Ans. The Compilation feature of Magento will allow you to compile all files of a Magento installation in order to create a single include path to increase performance. The performance increase is between 25%-50% on page loads. In order to use this tool, the directory ‘includes’ and the file ‘includes/config.php’ must both be writable.

Important: Before you make any changes to your Magento installation you should always disable compilation. Once the changes are made, run the compilation process, and then enable it.

This tool should be disabled before the extension installation to avoid potential problems. You can temporary disable it in Backend » System » Tools » Compilation by clicking the Disable button and the Compiler include path will be disabled. Then, after the extension installation run the compilation process again.

39. What is the addAttributeToFilter Conditionals in Magento?

Ans. In Magento we can use addAttributeToFilter Conditions same as WHERE in SQL
Below are the all condtions

Equals: eq


$_products->addAttributeToFilter('status', array('eq' => 1));

Not Equals – neq


$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));

Like – like


$_products->addAttributeToFilter('sku', array('like' => 'UX%'));

One thing to note about like is that you can include SQL wildcard characters such as the percent sign.

Not Like – nlike


$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));

In – in


$_products->addAttributeToFilter('id', array('in' => array(1,4,98)));

When using in, the value parameter accepts an array of values.

Not In – nin


$_products->addAttributeToFilter('id', array('nin' => array(1,4,98)));

NULL – null


$_products->addAttributeToFilter('description', 'null');

Not NULL – notnull


$_products->addAttributeToFilter('description', 'notnull');

Greater Than – gt


$_products->addAttributeToFilter('id', array('gt' => 5));

Less Than – lt


$_products->addAttributeToFilter('id', array('lt' => 5));

Greater Than or Equals To- gteq


$_products->addAttributeToFilter('id', array('gteq' => 5));

Less Than or Equals To – lteq

 $_products->addAttributeToFilter('id', array('lteq' => 5)); 

40.What permissions required for file and folder In Magento ?

Ans. Normal Operation

For the normal operation or installation of a Magento store, only 2 folders need to be writable:

/media – for web accessible files, such as product images
/var – for temporary (cache, session) and import/export files

Installation

During installation Magento Install Wizard will create app/etc/local.xml file which contains database configuration and global encryption key for your Magento copy.

Meaning app/etc folder has to be writable to web service.

Web based MagentoConnect manager

If you wish to use web based downloader for installation, upgrades or MagentoConnect extensions installation, you will need to have write permissions on ALL magento files including the root Magento folder.

Files and folders will need to be returned to 655 non-writable permissions after installation.

41.Why magento is slow ?

Ans. Magento is slow due to below thing

1. EAV structure of magento database, even for retrieving single entity the query becomes very complex .

2. Magento’s template system involves a lot of recursive rendering

3. Huge XML trees built up for layout configuration, application configuration settings

42) Explain how you can move Magento to another Directory?

To move Magento to other Directory you have to follow the following steps.

  • Suppose you have Magento installed in the following location

http://www.guru99.com/store/

  • On visiting your site, you want Magento to be the first thing to come up

http://www.guru99.com

  • Let assume you have a directory structure like this

/home/username/public_html/

  • Which means Magento would be installed here

/home/username/public_html/store/

  • Login to the backend of the Magento first and go to

System -> Configuration -> Web

Update the Secure and Unsecure URL for your store and then link to your site via SSH and then go to the directory, where you will be shifting Magento

cd public_html/

  • Now, transfer all the files from the store directory to the directory you are in

mv store/* store/.htaccess

  • Delete the cache data

rm –vf var/cache/

Now Magento is moved to another directory.

Faced Interview Questions:

1.Magento-when to use Mage::getResourceModel and Mage::getModel

Mage::getSingleton()

Mage::getSingleton() will first check if the same class instance exists or not in the memory. If the instance exists then it will return the same object from the memory. So Mage::getSingleton() is faster than Mage::getModel().

Example

$product1 = Mage::getSingleton(‘catalog/product’);
$product2 = Mage::getSingleton(‘catalog/product’);

$product1 and $product2 both will share same memory of OS and return only one instance each time.

Mage::getModel()

Mage::getModel() will create a new instance of an object each time even such object exists in configuration.

Example

$product1 = Mage::getModel(‘catalog/product’);
$product2 = Mage::getModel(‘catalog/product’);

$product1 and $product2 both have different instant of same object and also occupy different memory

Mage::getResourceModel()

As far as I know, all collections in Magento are resource models. They are instantiated by

Mage::getResourceModel()

or

Mage::getModel()->getCollection()

It doesn’t really matter which function you use; the latter one simply calls the first one. The Magento team simply chose to make collections part of the resource, probably because collections need to query the database a lot. Usually, you will not have to call Mage::getResourceModel() for anything else than collections.

2.Magento config.xml system.xml adminhtml.xml

The config.xml files contain global configuration information for Magento, available to all Magento “areas”. In the beginning, there were no adminhtml.xml configuration files. This information was located in config.xml. Later versions of Magento broke this information out into adminhtml.xml files, and only merged these files with the other config.xml files when the system was serving backend admin pages.

The system.xml files are not a part of the global configuration. They’re a separate system for automatically building UI in the backend application for setting system configuration values.

How Magento loads these files is a long involved tale that’s not appropriate for a Stack Overflow answer. I have a four article series that covers this in detail if you’re interested in that sort of thing.

The short version is config.xml files are loaded here

#File: app/code/core/Mage/Core/Model/Config.php
$this->loadModulesConfiguration(array(‘config.xml’,$resourceConfig), $this);

The adminhtml.xml files are loaded here

#File: app/code/core/Mage/Admin/Model/Config.php
Mage::getConfig()->loadModulesConfiguration(‘adminhtml.xml’, $adminhtmlConfig);

and system.xml files are loaded here

#File: app/code/core/Mage/Adminhtml/Model/Config.php
$config = Mage::getConfig()->loadModulesConfiguration(‘system.xml’)
->applyExtends();

3. What are “magic methods” in Magento?

Magento uses __call(), __get(), __set(), __uns(), __has(), __isset(), __toString(), __construct(), etc. magic methods. You can find more details inside class Varien_Object

class Varien_Object  located in lib/Varien/Object.php

4.What is Magento’s Compilation feature?

Ans. The Compilation feature of Magento will allow you to compile all files of a Magento installation in order to create a single include path to increase performance. The performance increase is between 25%-50% on page loads. In order to use this tool, the directory ‘includes’ and the file ‘includes/config.php’ must both be writable.

Important: Before you make any changes to your Magento installation you should always disable compilation. Once the changes are made, run the compilation process, and then enable it.

This tool should be disabled before the extension installation to avoid potential problems. You can temporary disable it in Backend » System » Tools » Compilation by clicking the Disable button and the Compiler include path will be disabled. Then, after the extension installation run the compilation process again.

5. The Config.xml

Module Activation File:

The Activation file is the file that activates the modules, and tells Magento, where to look for the module, as well as dependencies.

The Activation files are all put in app/etc/modules/

Technically, it doesn’t matter what you call this file because all files in this folder are parsed, but the naming convention is Namespace_Modulename.xml. Inside the file however, does matter.

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Namespace_Modulename>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Catalog/>
            </depends>
        </Namespace_Modulename>
    </modules>
</config>

active:[true, false] this actives or de-activates the module. Note: this is the only place where you can really deactivate the module. In the backend, under Configuration => Advanced => Advanced => “disable module output” will NOT disable the module. It merely stops that module from outputting any html to the page. This is the way to disable a module from showing without breaking functionality, but in most cases, when you need a module disabled, you will have to find the module activation file.

codePool: [local, community, core] note the capital P here, codepool as a variable will not work it must be codePool. This is the root folder Magento will look for this module in. The code pools are loaded in order: core, community, local. Any overrides you wish to do with modules should be done in local.

depends: [ (Any other Module Namespace_Name)] this is the list of dependant modules that must be active and loaded before this module can function. Magento does checking on this variable so make sure your module includes all the relevant dependancies.

Module config.xml

The next most important configuration xml files in Magento are the module etc/config.xml files.

Once the Module is activated, we can then start building out our module.

app/code/local/Namespace/Modulename/etc/config.xml

We start with a declaration of which module this will match the module activation file exactly, then state your version number.

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Namespace_Modulename>
            <version>1.0.0</version>
        </Namespace_Modulename>
    </modules>
    <global>
          <models>
                <modulename>Namespace_Modulename_Models</modulename>
          </models>
          <blocks>
                <modulename>Namespace_Modulename_Blocks</modulename>
         </blocks>
          <helpers>
                <modulename>Namespace_Modulename_Helpers</modulename>
          </helpers>
    </global>
</config>

global: [models, blocks, helpers, resources, index, events, eav_attributes*]this is all the configuration that defines the global specs of the module. There are a few areas in magento that override each other, but this is the global config.

*eav_attributes can be defined in configuration, but it is more commonly accepted to put them in your resrouces setup script.

global : models: [modulehandle => classname] Here is where you are defining where Magento is to look to find you code for all your models. Because of the autoloader in Magento, you’re both defining a path and a Class name, by doing this, for Magento to load this class, it must be in the correct path name for the autoloader to find it.

global : blocks: [modulehandle => classname] Here is where you are defining where Magento is to look to find you code for all your blocks. Because of the autoloader in Magento, you’re both defining a path and a Class name, by doing this, for Magento to load this class, it must be in the correct path name for the autoloader to find it.

global : helpers: [modulehandle => classname] Here is where you are defining where Magento is to look to find you code for all your helpers. Because of the autoloader in Magento, you’re both defining a path and a Class name, by doing this, for Magento to load this class, it must be in the correct path name for the autoloader to find it. Note: with helpers, the default helper will always be Data.php

Module Rewrites

Note: Most module rewrites aren’t actually required, with many situations able to be solved with events in Magento, to use events to extend functionality.

This is Magento’s take on the Standard Factory Methods that you see in many other frameworks. Because Magento is so heavy based on configuration, even the class factories refer to the configuration before loading. This means, that every module in Magento can be extended or completely overwritten with ease, without breaking functionality.

Module rewrites are all configuration based.

<?xml version="1.0" encoding="UTF-8"?>
<global>
    <models>
        <catalog>
            <rewrite>
              <product>Namespace_Modulename_Models_Product_Override</product>
            <rewrite>
        </catalog>
    </models>
<global>

When Magento reads its configuration files, every module is parsed into one (very big) configuration file, and pushed through to the appropriate code handlers.
Events

With PHP not natively supporting events, Magento has coded an events system that runs in the Framework, this is configuration based, unlike most event driven systems. To register an event observer with the system, you need to specify it in your configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<config> 
  <frontend>
        <events>
            <catalog_product_is_salable_after>
                <observers>
                    <neoware_restrictproductcheckout>
                        <type>model</type>
                        <class>neoware_restrictproductcheckout/catalog_product_observer</class>
                        <method>onCatalogAfterIsSalable</method>
                    </neoware_restrictproductcheckout>
                </observers>
            </catalog_product_is_salable_after>
        </events>
    </frontend>
</config>

To find which event you need to use as a handle, you need to find it in code, which to be honest can be very time consuming. There are some default events that occur on several load points, however I don’t have a list for you here, with many occurring in the abstract layer (meaning that any class that extends from those classes also trigger those events).

There are a few rules about observers though, the model that you specify in the configuration, just has to be a normal model (however the convention is to have one observer class named observer), and can contain any function, as long as it has a parameter type declaration within the function, like below.

function onCatalogAfterIsSalable(Varien_Event_Observer $observer){

	$productToEdit = $observer->getProduct();

	$productToEdit->setName($productToEdit->getName() + “ Is Awesome”);

}

Any Change that’s done here is persisted on that entity that was passed to it, so when you’re done there’s no need to return anything.

Categories: Magento

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *