Create Frequently Used Functions in Magento Development

View: 808    Dowload: 0   Comment: 0   Post by: hanhga   Category: Magento template   Fields: Other

One distinguishing characteristic of Magento is its layout feature.

This is an added layer which is not present in most other CMSs. Magento layouts are defined through XML tags. As a best practice, custom XML code is usually added in the local.xmlfile present in the layout folder, as it is the file which is loaded at the very last, and functions written in it override all other functions.

Using XML code, we can add different CSS and JS files in Magento blocks. One benefit of using this approach is that we can ensure that CSS and JS files are only loaded in layouts which need them. This way we can avoid unnecessary loading of CSS and JS files, and thus reduce page load time.

We can use the following code to add a CSS file in any layout block.

<reference name="head">
  <action method="addItem">
    <params />

Here the reference name contains the name of the block where we'll add that CSS/JS file. In this example we're adding a CSS file, so the type parameter wasskin_css, but if we needed to add a JS file, the type parameter would change toskin_js. The <params /> tag is intentionally left empty here.

Using the code below you can unset a child of one parent block and assign that child block to another parent block. For instance you can unset the poll block (child block) from the sidebar (old parent block) and assign that poll block to any new parent block, like the footer.

<!-- Removing Block from old parent -->
<reference name="old_parent">
  <action method="unsetChild">
<!-- Now adding it to new parent -->
  <action method="insert">

If you only need to remove a block, you can use just the first part of the above code. Similarly, if you only need to assign a new block to already existing block, just use the second part of the code.

CMS blocks are particularly handy in template creation, because they give a non‑technical user the power to easily add content in this block from the admin panel. CMS blocks can be inserted in any layout block using the code below. 

<!-- Inserting CMS block -->
<block type="cms/block" name="relevant_name">
  <action method="setBlockId">

Another important function which is quite frequently used in XML files is assigning templates to different layout blocks. You can do that easily by using the code template below.

<!-- Insert template file -->
<block type="cms/template" name="relevant_name" template="page/html/template_file.phtml"/

If you already have some template assigned and want to change it, you can use this code:

<!-- Change page template -->
<reference name="root">
  <action method="setTemplate">

Although XML files are an important part of any Magento template that defines template layouts, PHP files are the real building blocks which do the actual task of filling up those layout blocks with useful content. 

These are the functions which are used throughout the template pages.

We can use two different approaches to generate many of these URLs. One is by using getURLs (like getBaseUrlgetSkinUrl, etc.), and the other is by using a helper/model class. To keep things simple here, we'll try to use the getURL approach in most cases. For example, to get the store URL you can use this simple function:

$url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

Similarly, we can generate the URL of the current page like this:

$url = Mage::helper('core/url')->getCurrentUrl();

In the same fashion, we can dynamically generate the URL of any specific page using the code below:    

$url = $this->getUrl('page.html');

The following two approaches can be used to access any file in the skin directory. As most CSS, JS, and image files reside in the skin directory, references to this location are made hundreds of times in every template.

$url = $this->getSkinUrl('images/file.jpg');

If you intend to fetch any resource from skin directory through secure access, you can just pass an additional parameter of array('_secure'=>true) to accomplish that. 

$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));

Using the getBaseURL() function we can also access several other directory URLs. Here are some examples:

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); //creates media directory path i.e. mydomain.com/media
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS); //creates JS directory path i.e. mydomain.com/JS
<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);?> //another way to create URL for skin directory path i.e. mydomain.com/skin

While creating/editing templates for Magento, quite frequently we have to insert static text in different places. It could be an instruction for users, some button text, or anything else. To ensure that it is ready for translation into other languages, I advise you to put the content like this:

$text = $this->__('Content');

Product and Category pages are the most important part of any eCommerce CMS. While creating Magento templates, you'll be working on these pages most of the time. Here I've listed some frequently used functions for these pages, which will facilitate you in your development endeavors.

When you are on a Category page, you can use this function to load the current category.

$_category = Mage::getModel('catalog/layer')->getCurrentCategory();

You can also use this function to serve the same function:

$_current_category = Mage::registry('current_category');

Sometimes you need to reference a category through its ID number. This function will come in handy in instances like that:

$_category = Mage::getModel('catalog/category')->load($category_id);

As with categories, you can also access a product through its ID, using the function below:

$_product = Mage::getModel('catalog/product')->load($product_id);

In Magento, products have another unique identifier other than ID, and that is SKU. You can also reference products via their SKU using this function:

$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $product_sku);

You can access the product images with customized parameters (size, style, etc.) using this function. Please note that this function will only work in a product/view/media.phtml file.

$this->helper('catalog/image')->init($_product, $_image_attribute_name)    ->keepFrame(false) // if true, will ensure that image has dimensions in $width/$height
   ->constrainOnly(true) // if true, will ensure that image's height or width do not exceed its actual width or height
    ->keepAspectRatio(true) // if true, will guarantee that image's height, width ratio remain intact
    ->resize($_image_width, $_image_height); // parameters given there are used for as lengths for width and height.

The Cart and Checkout pages are also very important parts of an eCommerce website. The functions related to them will not only help you in creating these pages, but also assist you in showing cart details in the sidebar, footer, or header.

Using the function below, you can use the count of total items in the cart.

<?php $_cartQty = $this->getSummaryCount()? $this->getSummaryCount() : 0 ?>

You can loop through the items recently added to the cart using the code below:

<?php $_items = $this->getRecentItems() ?>
<?php if(count($_items)): ?>
    <?php foreach($_items as $_item): ?>
            <?php echo $this->getItemHtml($_item) ?>
    <?php endforeach; ?>
<?php else: ?>
    <?php echo $this->__('You have no items in your shopping cart.') ?>
<?php endif ?>

Here I've only shown the PHP code. You can insert the HTML in it as per your style requirements.

You can also show the subtotal of the items added in the cart by using this function:

<?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal()) ?>

Lastly, you can use these two functions to generate dynamic links to the checkout and cart pages respectively:

<?php echo $this->getCheckoutUrl() ?> // Generates Checkout page URL
<?php echo $this->getUrl('checkout/cart'); ?> // Generates Cart page URL

CMS Pages are the pages of the store where user-created content is published. Some examples of such pages are the About Us page, the Privacy Policy page, and the Terms & Conditions page. Though these pages usually serve as a place to put user-created static content, many times you have to enter dynamic content in them, for example a dynamically generated link to the store URL or the skin files URL. Below we'll discuss how to handle such scenarios.

Please note that the PHP functions explained above do not work in the CMS pages content area.

Just as we use Mage::getBaseUrl(); in the PHP template files to access the store URL, we can use this function in CMS pages to access the homepage URL:

{=store url=""=}

Similarly, the following function is the alternative to the $this->getSkinUrl('images/imagename.jpg'); function to be used in a CMS page:

{=skin url='images/imagename.jpg'=}

Likewise, this function is similar to the $this->getUrl('mypage.html'); function, to access a specific page.

{=store url='mypage.html'=}

The media files can also be easily accessed from CMS pages, using the function given below:

{=media url='/imagename.jpg'=}

You can also call a Magento static block from within a CMS page content area, using this function:

{{block type="cms/block" block_id="your_block_identifier" template="cms/content.phtml"}}

Caching is also an important part of Magento, like any other CMS. The model controlling the caching subsystem in Magento is Mage_Core_Model_Cache. To access the cache, we use it through an already instantiated object accessible at Mage::app()->getCache(). Here I'll enlist the cache functions used to save, load, and clear cache objects.

To load a cache object, we use the getCache() function:

$cache = Mage::app()->getCache();

After cache object loading, we use the following function to save an item in it.

$cache->save($string, $key, array($tag), $lifetime);

An example of such saving could be:

$cache->save("Save this string", "string_key", array("string_tag"), 60*60);

In the above example, we save the string Save this string into cache. In order to access that in future, we give it a key (string_key), then we give it a tag (string_tag), and lastly, we give it lifetime of 1 hour (60*60 seconds).

Once we are done saving the value in cache, we can now retrieve it by using theload(); function and passing on the string_key as a parameter:


Similarly, we can remove that entry saved in cache by using the remove(); function, and passing on the string_key as a parameter:


You may be wondering by now, of what use is the array we used for tagging. The purpose of such tagging is to perform a function on mass scale, by referring to all the cache entries which have a particular tag assigned to them. For instance, if we use the following code, it'll delete all the entries in the cache that have the string_tagarray assigned to them.


Since we've explained cache functions, I guess mentioning sessions becomes mandatory. In Magento, session variables can be as easily saved, loaded and removed as cache variables. I'll try to explain that with two examples.

$msgOne = "This is the First Message";
$msgTwo = "This is the Second Message"; 

Now we have saved into cache $msgOne as ValueOne and $msgTwo as ValueTwo. In order to retrieve these two, we'll use these functions:

$retrievedValueOne = Mage::getSingleton('core/session')->getValueOne();
$retrievedValueTwo = Mage::getSingleton('core/session')->getValueTwo();

Here I have deliberately saved and loaded two variables into session, so that you can understand how the set, get, and unset prefixes work.

Just like saving and loading, the removal process is fairly similar for session variables:


Lastly, you can use this handy function to check whether a customer is logged in or not:

$logged_in = Mage::getSingleton('customer/session')->isLoggedIn();

Well, as I said earlier, Magento is a huge CMS, and its functions cannot be piled up in a single post. But I've tried my best to compile a list of the most frequently used functions, and I've also tried to briefly explain how they work and what parameters they expect. A careful analysis of these functions will also give you some understanding of how Magento functions work. As a parting thought, I would encourage you to explore the XML and PHTML files of the Magento base theme, to learn more about Magento functions.



Create Frequently Used Functions in Magento Development

One distinguishing characteristic of Magento is its layout feature.

Posted on 19-01-2016 


To comment you must be logged in members.

Files with category

File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd