Design Patterns

Posted: January 8, 2014 in Magento

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.

1
$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.

1
$category = Mage::getSingleton(‘catalog/session’);

Registry:

It is a way to store information throughout your application.

1
2
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.

1
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.

1
Mage::dispatchEvent(‘event_name’, array(‘key’=>$value));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<config>
    <global>
        <events>
            <event_name>
                <observers>
                    <unique_name>
                        <class>Class_Name</class>
                        <method>methodName</method>
                    </unique_name>
                </observers>
            </event_name>
        </events>
    </global>
</config>

Object Pool:

It is used to reuse and share objects that are expensive to create.

1
2
$id = Mage::objects()->save($object);
$object = Mage::objects($id);

Iterator:

It is used to traverse a collection and access the collection’s items.

1
Mage::getModel(‘catalog/product’)->getCollection();

Lazy Loading:

It is used to defer initialization of an object until the point at which it is needed.

1
2
$collection_of_products = Mage::getModel(‘catalog/product’)
->getCollection();

Decorator:

It is used to extend or modify the behaviour of an object at runtime.

1
<script type=”text/javascript”>decorateTable(‘product_comparison’);</script>

Helper:

Multiple methods are available for use by other objects. Here you can use core’s helper methods from anywhere in the application.

1
Mage::helper(‘core’);

Service Locator:

Allows overrides or renamed physical resources (e.g. Classes, DB tables, etc)

1
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.

1
$collection->getFirstItem();

Leave a comment