Showing posts with label magento. Show all posts
Showing posts with label magento. Show all posts

Wednesday, August 27, 2014

Optimizing Magento for Best Performance

Speed and performance can make or break your online store. Now that Google officially announced they will be considering site’s speed on ranking websites and our eager and impatient customers just can’t wait to spend their money on our online store.
There are several sides to look at when optimizing Magento or any other content management systems. The hardware, softwares and ofcourse the network which where data travels to.
While methods to increase site speed range from Magento’s backend setting, the theme & modules used to the server or hosting the Magento’s system is on. This post will cover purely Magento’s installation. So here are some few ways to greatly increase Magento’s speed.

Theme Development Procedure

A well developed theme results in faster loading times. Too much bloat and bounce rates will be sky high.

Never ever hack the core files, ever!

I’ve seen this too many times and it’s something really unpleasant. Lots of developers don’t follow the Magento’s standard development procedure and hack the code, which can be quicker but dirty way to work. Update will surely break your store and can result in errors which will slow down the site.

All other coded files belong to either /local/ folder which contains your files and /community/ folder which contains third-party modules.

Unoptimized Images Are Often The Culprit

Product images should be saved for web as PNG or JPEG to lessen the file size. This tools can help optimize the image’s file size:
TinyPNG
Yahoo SmushIt

CSS Sprite The Theme’s Images

CSS Sprite is a method of combining the image into a single one and then calling them one by one through CSS. This method will greatly reduce the HTTP request which in turn gives us a faster Magento store. SpriteMe can help us with this task efficiently.

Remove unused codes

Unused codes within the template files will result in uncalled for queries & requests. Removing unused codes will results in faster page loads and easier to maintain codes.

Minify the CSS & JS

Minifying CSS and JS code before going live for our customers is critical as it will greatly reduce the file size needed to be served.

Social media plugins significantly slow down the site

Most social media plugins require too much Javascript, while their function is just to serve a simple button. It is often best to embed social media buttons into the theme instead. This goes for majority of content management systems.

Administrator Settings

This optimizitation are easily accessed via the administrator dashboard menu and can often times be overlooked even on most experienced developers so make sure its on your launch checklist.

Enable cache

Cache is usually turned off while developing or installing something new. So always double check if caching is enabled.

You can enable/disable the cache via the Magento admin then go to System > Cache Management. Select them all then enable it from the dropdown then submit.

Merge CSS and JS file

Magento has tons of JS files and CSS files required for the theme and third-party modules. Merging them into a single file will make the online store speed up as it will lessen the requests made and the size of the files.

Merge them via System > Configuration > Advanced > Developer then hit yes for Merge Javascript files and Merge CSS files.

Enable compilation

Get up to 50% performance boost by enabling compilation by going to System > Tools > Compilation and click enable. What it does is it will compile all the PHP files needed for Magento to run into a single file instead of calling each part one by one in order to create a single request which can significantly improve Magento’s performance.

Just remember to disable this feature anytime you make any code level changes or installing modules and recompile every after changes, and don’t forget that.

Use Flat Catalogs

Flattening the catalog will join the product and category information into a single database table making it faster. Database is similar to a spreadsheet consist of tables and rows which contain the needed information. So often times Magento has to search for multiple tables and rows to provide the user with the requested information which can seriously slow it down.

Flatten it by going to System>Configuration>Catalog>Frontend. Select Yes for both Use Flat Catalog Category and Use Flat Catalog Product

Avoid Layered Navigation When Possible

While a great and critical feature, often times it does’nt really add value to our customers at all such as having few products with no attributes in a category. It’s best if left disabled, this feature is quite resource intensive.

Layered navigation can be turned on or off via Categories then choose the specific category and set the Use Anchor to Yes or No.

Disable Unused Modules

Some modules can safely be left disabled if not needed, instead of consuming those precious loading speed and resources. The Authorize.net module, GoogleCheckout, Tags, Newsletter, Wishlist, Phoenixs module to name some but it is critical to review the system’s requirements for a truly optimize experience.

Conclusion

This tips will surely make each Magento install in top performance. However always remember in terms of totally optimizing Magento there is no single way of doing it as Magento is a highly flexible system and each business is unique and has different needs.

Wednesday, August 6, 2014

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

For more information about magic methods Click Here

Set, Retrieve and Unset Session in Magento

Set:


$mySession = ‘Hello India';
Mage::getSingleton(‘core/session’)->setmySession($mySession);

 

To Retrieve:


$mySession = ”;
$mySession = Mage::getSingleton(‘core/session’)->getmySession();

 

To Unset:


Mage::getSingleton(‘core/session’)->unsmySession();


Here get(), set(), uns() are Magic Methods. To Know more Details about Magic Method Click Here 

How to migrate magento from one server to another?

Several way you can move server, one of the most easiest way.

Follow the below Step:

1) Back up the files in the server
2) Export the Databse
3) Move the files to the new server
4) Import the databse to the new server
5) Edit the database details . please update the file “app/etc/local.xml”, with the latest Database details
6) Modify the table core_config_data (Replace old server name with new one).
7) Delete the files in “var/session” and “/var/cache”

How to Run Magento Code Externally?

Sometimes need to use Magento functions and classes from outside of the Magento platform. Please check the following code.

<?php
require_once(‘app/Mage.php’); //Path to Magento
umask(0);
Mage::app();
// Insert your code

 
If you want run this script just save at your own name like upload.php
Hope it will help you.

Advantages and Disadvantages of Magento

Advantages of Magento

  • It is open source, so it’s easy to be popular and everyone can use it.
  • Since Magento is 100% open source platform, lots of Magento extensions including free and paid ones are available to enhance of the power of   Magento Ecommerce on your store.
  • Magento is built to scale from 1 to a million, avoiding common pitfalls for developers. Code re-use, maintainability, debugging, support, etc. are all huge, expensive problems that eCommerce solutions providers must tackle. Magento makes them all a breeze. Magento is powerful and effective.
  • Magento handles concepts properly and in an organized manner. Stock Magento comes with Simple, Configurable, Grouped, Bundled, Virtual  and Digital Products. You can use it to sell amusement park tickets and digital music at the same time, without any extensions.
  • Magento can have many extensions which support for the development of the online store.
 

The disadvantages of Magento

  • Magento runs PHP. Magento is architected like an enterprise java application, but its codebase is written in PHP. Users have complained that the Magento is relatively slow than other ecommerce solutions.
  • It is a complex system and not one that is easy to work with. If it does not use object-oriented programming or other best practices because it has a heavy layered and complicated code that takes a lot of time to learn and make changes accordingly. Therefore, to get a job done properly and efficiently, you need to have a proper budget in order to work with Magento.
  • You need to have a good hosting environment and store management in order for Magento to run. If proper hosting environment is not set-up, you can experience problems with speed.  Unlike simpler systems which can work anywhere, such as WordPress, Magento performs poorly if the website services are not as required, which means you need to have good server along with a good team to set and maintain server.
  • Magento is intensive resource and requires much space and memory.
  • Installation is not as intuitive as it should be in admin area. You should use the option of safe mode during installation

5 Most Common Magento Coding Issues to Optimize Your Site for Performance

  1. Calculating the size of an array on each iteration of a loop
  2. SQL queries inside a loop
  3. Loading the same model multiple times
  4. Redundant data set utilization
  5. Inefficient memory utilization

Magento SEO guideline

Search Engine Optimization (SEO) is a set of actions merchants take to make sure their e-commerce store shows up when customers search for their products through a search engine, whether it be Google or any other search engine. This can make a big difference in your store's visibility and sales.

Content Checklist

1. Product names and descriptions
Do your products contain the search keywords you want to attract? If you have a large catalog and tend to upload your product names and descriptions from your suppliers, you should make sure that you are customizing the product names, descriptions and short descriptions to include important keywords. The same rules apply to category names and descriptions.

2. CMS pages
Writing and creating content for the web is very important as having informational pages with well-written, keyword-rich content help you attract customers interested in your products. Magento’s CMS pages are a great place to feature how to product guides, products videos or summaries of their content, and other types of information you find to be relevant.

3. Blog
Blogs are important places to feature high-velocity content, which can help improve your rankings. Ideas for the holidays, comments on topics trending on twitter or in the news media are great subjects for your blog and will help you attract short-term search engine traffic. While Magento itself does not offer blog functionality as a core function, there are several extensions available that allow you to incorporate a blog in your store.

4. Reviews
User-generated content is a magnet for search engines, and product reviews by actual purchasers are a great way to encourage users to add information to you site (besides the fact that shoppers find them useful). For taht purpose you can use the built-in review system that comes with Magento.

Effective use of Meta Data
Meta Data is information on your website that is not visible to your users but is used by search engines to display results. Optimizing your meta data will not only have a nominal effect on search engine results, but it will help improve your click-through rates when your results are displayed. The meta-title shows up as the link text and the description is the text below it on most search engines.
Meta-titles should be approximately 60 characters in length and descriptions should be limited to 155 characters. Note: Magento shows a 255 character limit, but search engines have recently decreased the number of characters they display in search results.

Down with the keyword strategy
In Magento and many systems there is a space to enter keywords about a specific page. In the old days of the web, search engines used this information when determining page rankings. However, all major search engines have disavowed the use of this field because of rampant abuse by keyword spammers. In fact, that keyword field is now a negative as it signals to your competitors what your keyword strategy is. We highly recommend you remove any text you have in the keywords field.

Meet canonical tags
Canonical tags help you avoid communicating duplicate content to Google and the other search engines. Magento takes care of them for you automatically. You just need to make sure you have them turned on in System > Configuration > Catalog > Search Engine Optimizations.
Be sure to choose YES next to both Use Canonical Link Meta Tag selections.

What is your site about?
Focus the search engines on the relevant sections of your site as you don’t want Google to crawl your site and index your account log in, cart, checkout and other pages as they confuse Google as to what your site is about.

We recommend a 3-pronged strategy
  • A good Robots.txt
  • Submit an XML sitemap
  • Use robots meta tags
A well-crafted robots.txt file should be sitting on your server. Google has a nice explanation if you aren’t familiar with it, but it basically tells search bots to ignore parts of your site. If you don’t have a robots.txt file on your server, the search engines may get confused trying to index your site. To find out if you have one, simply add robots.txt to the end of your url, for example, “www.yourstoresdomainhere.com/robots.txt”. If you get a 404 error instead of something that looks like this, you don’t have one!

Another thing to do is submitting a sitemap to Google and Bing webmaster tools accounts. There is a great blog article on the mechanics of it. It doesn’t require any tech knowledge to set up, though you may have to adjust the permissions of a folder on your site. Your xml sitemap will help the search engines focus on the important pages of your site.

Image research has shown that page load times on retail sites are increasing. As we cram more and more code and content into a single page thinking to increase appeal, we may actually increase bounce rates and sink our search rankings. Google has been very open about its initiative to speed up the Internet hence punishing websites that take longer to load.

Tuesday, August 5, 2014

Code pool in Magento


Magento has three different codepools:

  1. Community
  2. Core
  3. Local

Core pool


First of all, this folder stores all the code that makes Magento so powerful, flexible and lovely. The chief rule of Magento development is that you should never make any changes in it. In other words, this folder belongs to Magento core developers only and if you are going to edit anything in this pool, their evil spirit could punish you even through the display.

Community pool


This folder belongs entirely to community developers. This is the right place for hundreds of 3rd party extensions, both free and paid, that can be found at MagentoConnect or available on extensions development store. So basically, if you have installed any extension, it must be in app/code/community/ only.

Local pool


If you have your own Magento-based store and want to make everything by yourself or you are a Magento developer and have a purpose to change the logic somehow, local pool is the place where everything should be done. If you want to override Magento extensions, blocks or methods, copy the necessary folders from the Core pool and do whatever you are inclined to do. Apply the same rule for custom extensions that are created specifically for the website – all code should be in local pool.

How the framework knows which code pools apply in particular module

Please look in app/etc/modules and open any of custom module file

<?xml version=”1.0″?>

<config>

<modules>

<Custom_Module_Name>

<active>true</active>

<codePool>local</codePool>

</ Custom_Module_Name>

</modules>

</config>

Here you can see line of in this custom module return local so Magento search this module in local code pools. Exactly like this if you check any core functionality module here we take example of Mage_ImportExport.xml here I saw you code snippets of this

<config>

<modules>

<Mage_ImportExport>

<active>true</active>

<codePool>core</codePool>

<depends>

<Mage_Catalog/>

</depends>

</Mage_ImportExport>

</modules>

</config>

Here you can see code pool is core.

How does the framework interact with the various codepools?

To identify the proccess let’s take a look at app/Mage.php

$paths[] = BP . DS . ‘app’ . DS . ‘code’ . DS . ‘local';

$paths[] = BP . DS . ‘app’ . DS . ‘code’ . DS . ‘community';

$paths[] = BP . DS . ‘app’ . DS . ‘code’ . DS . ‘core';

$paths[] = BP . DS . ‘lib';

Can We give the Code Pool Outside the “code” Directory in Magento ?

You can have your custom codepool by putting below line in your app/Mage.php

$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'custom';

What to Do if you wanted to create Custom codepool outside core directory ?

if you want to keep your codepool in app/custom then creating symlink for your codepool will be the easiest way. Infect you can place your codepool anywhere in your system.

This is how you will create your symlink(considering /home/ashok/public_html is your magento root directory)

ln -s /home/ashok/public_html/app/custom/custom/ /home/ashok /public_html/app/code/custom

Thursday, July 17, 2014

Magento isRecurring

/**
     * Whether there are recurring items
     *
     * @return bool
     */
    public function hasRecurringItems()
    {
        foreach ($this->getAllVisibleItems() as $item) {
            if ($item->getProduct() && $item->getProduct()->isRecurring()) {
                return true;
            }
        }
        return false;
    }

How to retrieve customer name/firstname in Magento

require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
   $customer = $session->getCustomer();
   echo $customer->getName();
   echo $customer->getFirstname();
}

Modify Magento TAX Calculation

Change the following file: magento\app\code\core\Mage\Tax\Model\Calculation.php


/**
     * Calculate rated tax abount based on price and tax rate.
     * If you are using price including tax $priceIncludeTax should be true.
     *
     * @param   float $price
     * @param   float $taxRate
     * @param   boolean $priceIncludeTax
     * @return  float
     */
    public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
    {
        $taxRate = 10;
  $taxRate = $taxRate/100;
  $this->insertInLog('taxRate', $taxRate);
  $this->insertInLog('price', $price);
        if ($priceIncludeTax) {
            $amount = $price*(1-1/(1+$taxRate));
        } else {
            $amount = $price*$taxRate;
        }
  $this->insertInLog('Amount', $amount);
        if ($round) {
            return $this->round($amount);
        } else {
            return $amount;
        }
    }


    /**
     * Insert in to Log Table. It helps to trace and stores in table
     *
     * @param   varchar $title
     * @param   varchar $desc
     */

 function insertInLog($title, $desc){  
  mysql_connect("localhost","root","");
  mysql_select_db("magento");
  $sql = "insert into log_tbl values('".$title."', '".$desc."', '".date("Y-m-d h:i:s")."')";
  mysql_query($sql);
 }

Magento – How to load static block?

setStoreId(Mage::app()->getStore()->getId())->load("static_block_name");

Magento shopping cart total

helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')
               ->getQuote()
               ->getGrandTotal()); 

Magento cart total + items

getSummaryQty();
//There are items in your cart

foreach(getQuote()->getAllItems() as $item) {
    $output .= $item->getName() ;
    $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2);
}
print $output;

Display Magento sub categories

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

    if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
    {
        // current category is a toplevel category
        $loadCategory = $currentCat;
    }
    else
    {
        // current category is a sub-(or subsub-, etc...)category of a toplevel category
        // load the parent category of the current category
        $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
    }
    $subCategories = explode(',', $loadCategory->getChildren());

    foreach ( $subCategories as $subCategoryId )
    {
        $cat = Mage::getModel('catalog/category')->load($subCategoryId);

        if($cat->getIsActive())
        {


            echo $cat->getURL().$cat->getName();
            echo $cat->getDescription();
            echo $cat->getImage();
       }
    }

Magento displaying store id

// display store ID
echo "Store ID = " . Mage::app()->getStore()->getStoreId();

Magento observer sales order

/**
 * Register an event trigger after the order has been saved
 *
 * Is triggered by sales_order_save_after event 
 *
 */
public function hookSalesOrderSaveAfter ($observer)
{
    $order = $observer->getEvent()->getOrder(); // returns the Mage_Sales_Model_Order Object
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); // Magento can only save attributes in admin mode
    $order->setVendor('LoremIpsum');
    $order->getResource()->saveAttribute($order, "vendor");
    $order->setCallToAction('ANC');
    $order->getResource()->saveAttribute($order, "call_to_action");
    $order->setKeycode('0x7474');
    $order->getResource()->saveAttribute($order, "keycode");
    return $this;
}

Wednesday, July 16, 2014

Magento How to add new products

require_once 'app/Mage.php';
Mage::app();
 
// instatiate Product
$product = Mage::getModel('catalog/product');
 
$product->setWebsiteIds(array(1));
$product->setSku('rand-sku-' . rand());
$product->setPrice(rand(100,2000));
$product->setAttributeSetId(4); 
$product->setCategoryIds(array(3));
$product->setType('Simple Product');
$product->setName('Product Name'.rand(1,200000));
$product->setDescription('The Product Description');
$product->setShortDescription('Brief Description');
$product->setStatus(1); 
$product->setTaxClassId('2');
$product->setWeight(0);    
$product->setCreatedAt(strtotime('now'));
 
/* ADDITIONAL OPTIONS 
 
   $product->setCost();
   $product->setInDepth();
   $product->setKeywords();
 
*/
 
$product->save();
 
// "Stock Item" still required regardless of whether inventory
// control is used, or stock item error given at checkout!
 
$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->loadByProduct($product->getId());
$stockItem->setData('is_in_stock', 1);
$stockItem->save();
 
header("Location: /checkout/cart/add/product/".$product->getId()."/); 

Magento auto add product custom options

// *Special note: make sure you check your sql table name, 
//  and change the option title from what i have below.

// rbanh special methods
private function rbanh_get_custom_option_id($product_id)
{
    $sql = "
        select 
            o.option_id 
        from 
            catalog_product_option o
        inner join
            catalog_product_option_title t on t.option_id = o.option_id
        where
            t.title = 'Shipping Description'
            and o.product_id = '".$product_id."'
        limit 1
            ";
    $data = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql);
    if (count($data) > 0)
    {
        return current($data[0]);
    }
    return false;
}

// rbanh special methods
private function rbanh_add_custom_option($product_id)
{
    // make the option active
    //$write = Mage::getSingleton('core/resource')->getConnection('core_write');
    //$write->query("update catalog_product_entity set has_options = 1 where entity_id='$product_id'"); 
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $sql  = "update catalog_product_entity set has_options = 1 where entity_id=?";
    $write->query($sql, $product_id); 
    
    $product = Mage::getModel('catalog/product');
    $product->load($product_id);
    $opt = Mage::getModel('catalog/product_option');
    $opt->setProduct($product);
    $option = array(
        'is_delete' => 0,
        'is_require' => false,
        'previous_group' => 'text',
        'title' => 'Shipping Description',
        'type' => 'field',
        'price_type' => 'fixed',
        'price' => '0.0000'
    );
    $opt->addOption($option);
    $opt->saveOptions();
    
    return $this->rbanh_get_custom_option_id($product_id);
}

 

Copyright @ 2013 PHP WORDPRESS MAGENTO .

Designed by Kcon Technosoft