Useful Snippets

Factory Methods

<?
Mage::getModel()
Mage::getSingleton()
Mage::getResourceModel()
Mage::helper()
Mage::getResourceSingleton();
Mage::getBlockSingleton();
Mage::getResourceHelper();

About Magento

<?php
Mage::getVersion()
Mage::getVersionInfo();
Mage::getEdition();

Check a Module is Enabled

Mage::helper('core')->isModuleEnabled('Module_Name');

Checkout


// Get the increment id of the current user's last order
$lastOrderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();

// Load the last order for the current user
$order = Mage::getModel('sales/order')->loadByIncrementId($lastOrderId);

Data store

<?php
Mage::register('name', 'value')
Mage::registry('name')
Mage::unregister('name')

Paths & URLs

<?php
Mage::getRoot(); // Application root absolute path
Mage::getBaseDir($type); // The base dir of the install pass in 'media', 'app', 'base', 'design', 'etc', 'lib', 'locale', 'skin', 'var', 'tmp', 'cache', 'log', 'session', 'upload', 'export'
Mage::getUrl($route, $params); // Get a url (uses core/url model), possible params are _secure => true, and _forced_secure => true


Mage::getBaseUrl($type); // The base url of the install

The following constants can be passed into the getBaseUrl() method:
Mage_Core_Model_Store::URL_TYPE_MEDIA
Mage_Core_Model_Store::URL_TYPE_LINK
Mage_Core_Model_Store::URL_TYPE_DIRECT_LINK
Mage_Core_Model_Store::URL_TYPE_WEB – Store URL
Mage_Core_Model_Store::URL_TYPE_SKIN
Mage_Core_Model_Store::URL_TYPE_JS
Mage_Core_Model_Store::URL_TYPE_MEDIA

<?php
Mage::getModuleDir($type, $moduleName); // Get the module path
$type can be 'etc', 'controllers', 'sql', 'locale'.  If manually including an controller file, use this method as they are not autoloaded.
Mage::helper('core/url')->getCurrentUrl(); // Get the current URL
Mage::helper('core/url')->getHomeUrl(); // Get the home URL
Mage::helper('checkout/url')->getCheckoutUrl() // Get the checkout URL
Mage::getUrl('checkout/cart') // Get the cart URL using getUrl

Formatting a string as a URL

Mage::getModel(‘catalog/product_url’)->formatUrlKey(‘string to be converted’);

URLs in a block

<?php
$this->getSkinUrl('path/to/resource.png'); // Normal
$this->getSkinUrl('images/ sampleimage.gif', array('_secure'=>true)) // Secure

Redirecting within a controller

<?php
$this->_redirect('module/controller/action')
$this->_redirectUrl('url')
$this->_redirectReferer()
$this->_forward($action, $controller = null, $module = null, array $params);

Alternate redirect method

<?php
$this->getRequest()->initForward()
    ->setControllerName('controllername')
    ->setModuleName('modulename')
    ->setActionName('actionname')
    ->setDispatched(false);

Store

<?php
Mage::app()->getStore(); // Get the current Store object

Config

<?php
Mage::getStoreConfig($path, $store = null); // Retrieve a config value, store is the default store by default
Mage::getStoreConfigFlag($path, $store = null); // Retrieve a boolean config value
Mage::getConfig() Get the config object

Observers & Events

<?php
Mage::addObserver($eventName, $callback, $data, $observername, $observerClass);
Mage::dispatchEvent($name, $data);

Exception

<?php
Mage::exception($module, $message, $code);
Mage::throwException($message, $messageStorage);
Mage::logException(Exception $e);

Logging

<?php
Mage::log($message, $level, $file, $forceLog); // Logging var/log - use file from dev/log/file
// Will be logged in system.log unless $file is specified.  Won’t be logged if dev/log/active is off in the admin, unless $forceLog is true
Mage::log($message, $level, $file, $forceLog);

Layout

<?php
Mage::app()->getLayout();

HTTP

<?php
Mage::helper('core/http')->getRemoteAddr(); // Get the user's IP address

Product Image Resizing

<?php
Mage::helper('catalog/image')->init($product, $attributeName, $imageFile = null)
->resize($width, $height)
->keepAspectRatio(bool) // The image won't be stretched
->keepFrame(bool) // The image won't be cropped
->constrainOnly(bool) // The image will only be scaled down
->getOriginalWidth()
->getOriginalHeight()

$attributeName is a media attribute. Incidentally, a watermark will automatically be added to catalog images if the admin control has been turned on.

Image Resizing Using Varien_Image

<?php
$_imageUrl = Mage::getBaseDir(‘media’) . DS . $image;

$imageResized = Mage::getBaseDir(‘media’) . DS . "resized" . $image;


$imageObj = new Varien_Image($_imageUrl);

$imageObj->constrainOnly(true);

$imageObj->keepAspectRatio(true);

$imageObj->keepFrame(false);

$imageObj->resize(140, 140);

$imageObj->save($imageResized);

Products

  • Products are assigned to a Website. Products aren’t visible unless they are.
  • Products can’t be set to enabled / disabled on a store view.
  • Store Groups can contain a different root catalog, but the same products will still be available.

EAV Attributes

// Load a product attribute object baset on its code (replace 'catalog_product' to load other attribute types
$attributeModel = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'attribute_code');

Outputting Product Attributes

<?php
// For Dropdowns:
$product->getAttributeText($attributeCode);

// For any attribute
$product->getResource()->getAttribute($attributeCode)->getFrontend()->getValue($product);

// Formatting Attributes
Mage::helper('catalog/output')->productAttribute($product, $attributeHtml, $attributeName);

Formatting attributes respects any product attribute settings such as encoding HTML output

Setup and Installers

  • data installers go in the module’s data/ folder
  • installers go in the module’s sql/ folder

Running indexers within installers

They won’t run properly unless the store is set to admin and the following is set:

Mage::register('isSecureArea', 1);
Mage::app()->setUpdateMode(false);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

Controller Events

The following are dispatched from the preDispatch method of Mage_Core_Controller_Varien_Action
controller_action_predispatch
– *controller_action_predispatch_routeName * Eg. controller_action_predispatch_catalog
– *controller_action_fullActionName * Eg. controller_action_predispatch_catalog_product_view

Controllers, Actions & Request Object

<?php
// Get the module, controller and action name separated by underscores. Used to attach design XML elements to pages. Eg. catalogsearch_result_index
Mage::app()->getFrontController()->getAction()->getFullActionName();

// Get the current action class (outside of the controller)
Mage::app()->getFrontController()->getAction();

Translate Inline & Emails

Before sending an email, translate inline should be turned off to prevent input boxes being rendered in the email’s contents. It should be turned back on afterwards.

<?php
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);

Routers

The flow of Magento’s routing begins from Mage_Core_Controller_Varien_Front which calls *dispatch** which then attempts to match against a router.

The standard routers included in Magento are:
– Mage_Core_Controller_Varien_Router_Standard (Frontend)
– Mage_Core_Controller_Varien_Router_Admin (Admin)
– Mage_Core_Controller_Varien_Router_Default (Default)

Which then sets the following on the request object:

<?php
$request->setModuleName($module);
$request->setControllerName($controller)
$request->setActionName($action)
$request->setControllerModule($realModule)
$request->setDispatched(true);

Store Information

Get the Admin Store Model

<?php Mage::getModel('core/store')->load('admin', 'code');

Get the Base Website

<?php Mage::getModel('core/website')->load('base', 'code');

Get the Admin Store ID (Constant)

<?php Mage_Store_Model_App::ADMIN_STORE_ID;

Reindexing

Reindex everything

<?php
/* @var $indexCollection Mage_Index_Model_Resource_Process_Collection */
$indexCollection = Mage::getModel('index/process')->getCollection();
foreach ($indexCollection as $index) {
/* @var $index Mage_Index_Model_Process */
$index->reindexAll();
}

Reindex a Particular Indexer

<?php
$process = Mage::getModel('index/indexer')->getProcessByCode('catalog_product_price');
$process->reindexAll();