Monday, 14 May 2012

Useful Functions for Magento Collection


There are different important functions that you can implement in your Collection object. The functions are present in Varien_Data_Collection_Db class. The class file is present in lib/Varien/Data/Collection/Db.php

Here are some of the functions that you can use in your collection object:-

/**
* Get Zend_Db_Select instance
*/
$collection->getSelect();

/**
* Get collection size
*/
$collection->getSelect()->getSize();

/**
* Get sql select string or object
*/
$collection->getSelect()->getSelectSql();

/**
* Add select order
*/
$collection->getSelect()->setOrder($field, $direction);

/**
* Add field filter to collection
*
* If $attribute is an array will add OR condition with following format:
* array(
* array('attribute'=>'firstname', 'like'=>'test%'),
* array('attribute'=>'lastname', 'like'=>'test%'),
* )
*/
$collection->getSelect()->setOrder($field, $condition);

/**
* Set select distinct
*/
$collection->getSelect()->distinct($flag);

/**
* Get all data array for collection
*/
$collection->getSelect()->getData();

/**
* Reset loaded for collection data array
*/
$collection->getSelect()->resetData();

/**
* Print and/or log query
*/
$collection->getSelect()->printLogQuery(true, true);

More functions below:-

Varien_Data_Collection_Db class extends Varien_Data_Collection class. Here are some more functions present in Varien_Data_Collection class:-

/**
* Get current collection page
*/
$collection->getSelect()->getCurPage();

/**
* Retrieve collection last page number
*/
$collection->getSelect()->getLastPageNumber();

/**
* Retrieve collection page size
*/
$collection->getSelect()->getPageSize();

/**
* Retrieve collection all items count
*/
$collection->getSelect()->getSize();

/**
* Retrieve collection first item
*/
$collection->getSelect()->getFirstItem();

/**
* Retrieve collection last item
*/
$collection->getSelect()->getLastItem();

/**
* Retrieve collection items
*/
$collection->getSelect()->getItems();

/**
* Clear collection
*/
$collection->getSelect()->clear();


Hope this helps. Thanks.

Saturday, 12 May 2012

Get More Traffic to Your Site - Avoid the Top 10 SEO Mistakes


In years of Internet marketing and scrutiny of the SEO tactics of the web, I've found this list of today's most common mistakes that lead to a site's poor performance. In most cases, simply NOT doing these things will result in a more profitable online business... Hey, sometimes it's not what you do, it's what you don't do! Enjoy and benefit from these tips.


1. NUMBER OF KEYWORDS PER PAGE - You may well be over working your SEO labors. If you are optimizing more than one target keyword per page, than you in all probability are. Keeping your targeted keywords to one per page will probably get you better results. In some cases you can do two, but you honestly should keep it to one if possible.


2. URL HAS NO KEYWORDS - You can't always determine the domain name of a client. And maybe the company brand is before now well-known and is comprised of no keyword phrases, but changing the company name is not a possibility. You could possibly, in this case, be able to get a new domain with search phrases in it and point it to the company's website.


3. TITLE TAGS WITHOUT KEYWORDS - If you have set your company trademark, mission statement or some other really cool thing in the title tag, and it doesn't hold any search phrases, you've missed a huge opportunity to optimize that webpage. Keywords are more essential to search engines than your company motto, no matter how likable or cool it may be.


4. META TAGS NOT FULLY UTILIZED - There are Meta "keywords", and then there's the Meta "description". You should use both to convey to the search engines like Google what your focus is. With the "description", compress keyword terms and phrases and company slogans or tag lines here. With the Meta "keywords", put in the exact keywords you want to use, but keep the amount down to under 8 or 10 keyword terms.


5. KEYWORD DENSITY IS TOO DENSE - Keyword stuffing is lousy, and if you cram your keyword phrases into every single possible opening on the page, internet search engines might consider that you are spamming and punish your rankings. It's best to keep your words and phrases density to less than 5%. Typically 2-3% is fine.


6. TOO MUCH REDUNDANCY BACK-LINK ANCHOR TEXT - If you're applying the back-links with keyword terms and phrases in your anchor text, you're doing far more than most, but if you are simply putting one or two keyword phrases into these back-links, you're hurting your cause. Diversify your anchor text. Use 5 or 10 keywords and phrases and distribute them out properly throughout the Internet for more effective outcomes.


7. WORSE THAN THE PREVIOUS MISTAKE, HAVING NO KEYWORDS IN YOUR ANCHOR TEXT - If you will be going to the trouble to write articles and blogs and you are attaching in plenty of back links to your site, good. However, if your back links are not employing keyword phrases as anchor text, you’re not obtaining a fraction of the effect you could.


8. BACK LINKS, TOO MUCH TOO FAST - Don't get too enthusiastic about your blogs and articles and just bathe the Internet with back links. You have to compile your back links at a more usual rate of say 50 or 60 a week. This will prevent the search engine's thinking you are a automated bot.


9. LINK SOURCE VARIETY - Be positive that you exploit as many resources as possible when Creating back links. Putting all of your eggs in one basket tips off the internet search destinations that you may perhaps be a spammer seeking for a short cut to high rankings.


10. KEYWORD RESEARCH - None of this is important if you are employing the wrong keyword terms and phrases in the first place. Make it a point to devote time researching your keywords. Be confident that you are using keywords that will convert into business and that they are not too aggressive for your budget.


Avoid these 10 common mistakes, and you'll be ahead of most of the competition.


Hope this will help !!!!! :)

Friday, 11 May 2012

How to select, insert, update, and delete data in Magento?


Here, I will be showing how to select, insert/add, update/edit and delete data in the Magento way. It’s about implementing the CRUD (Create Read Update Delete) concept. :)

Suppose, I have a database table named ‘news‘ with the following fields:-

id : int, auto increment, primary key
title : varchar
content : text
status : 0 or 1

Suppose, I have a module named ‘mynews‘. Here follows the code to select, insert, update, and delete data from the ‘news‘ table.

INSERT DATA

$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
$insertId = $model->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
echo $e->getMessage();
}


SELECT DATA

$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}


UPDATE DATA

$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
$model->setId($id)->save();
echo "Data updated successfully.";

} catch (Exception $e){
echo $e->getMessage();
}


DELETE DATA

$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
$model->setId($id)->delete();
echo "Data deleted successfully.";

} catch (Exception $e){
echo $e->getMessage();
}


In this way you can perform select, insert, update and delete in your custom module and in any magento code.

Hope this helps. Thanks.

How to clear the cache using code in Magento?


If you have made any modifications to your Magento store, they will not appear immediately unless you clear the cache.
Magento keeps its cache in /var/cache located inside the Magento installation directory. So, for example, if your Magento is installed in your main public_html folder, the cache will be in public_html/var/cache.
To clear the cache, simply delete everything from the /var/cache directory and then reload your website in your browser.
To clear all sessions, you can also delete everything from the /var/session folder within your Magento installation directory.
To clear cache in Magento using code, you can use one of some methods below:
Clear all cache files of Magento by the command: rm -rf var/cache/*

Clear by Magento’s code
Clear all frontend caches:
Mage::app()->cleanCache();

Clear cache by tag:
$tags = array("CONFIG");
Mage::app()->cleanCache($tags);


Clear all caches:
Mage::app()->getCacheInstance()->flush();

Hope this will help you !!!! :)

Thursday, 10 May 2012

Add Featured Products to Home Page in Magento


This article will show you an easy way to display products of your choosing on the home page.

1. Create a category to contain the featured products. Call it e.g. “Featured” or “Home Page”. Set “Is Active” to No. That way, it won’t display in the catalog menu.
2. After saving the category, please note what ID it gets. You can see it in the last part of the URL. If the URL ends with catalog_category/edit/id/8/, the ID is 8.
3. Add products for the home page to the new category.
4. Edit the Home Page (CMS → Manage Pages → Home Page) and add the following content, where 8 should be replaced by your category ID:

{{block type="catalog/product_list" category_id="8" template="catalog/product/list.phtml"}}

If you want a view that is different from the category lists, you can copy and modify list.phtml and change the path above.

Please note: In order to make this work for more than one block of products with different category IDs on the same page, you need to add the following code at the end of your phtml file(s):

Tuesday, 4 October 2011

Magento File Structure and Workflow


At a very high level, Magento is split into three main sections: skin, templates and code. Files are organized in the file system as follows:

Figure 1. Magento’s File Layout

/magento
   /app
      /code
         /community
            core code (PHP, XML)
         /core
            core code (PHP, XML)
         /local
            extensions, your modules (PHP, XML)
      /design
         /adminhtml
            backend themes (PHTML)
         /frontend
            frontend themes (PHTML)
         /skin
            skin (CSS, JS, images)
As you can see, there are many files in many places used to create functionality in Magento. To organize that functionality, Magento is split into modules, each of which provides a little functionality to the system. A module is comprised of several different types of files: configuration, localization, display information, controller code and information about models (usually database records). These files are also organized, this time according to MVC principles.
What that means effectively is that data, actions and presentation are split up and put into different places to keep them separate. That way, if you change a template in Magento, you don’t need to worry about the data models that make up the objects you use in that template. Here’s where the files for a single module are kept in the Magento tree:

Figure 2. The CatalogSearch module (from /app)

/code
   /core
      /Mage
         /CatalogSearch
            module code (see below)
/design
   /frontend
      /default
         /myTheme
            /layout
               catalogsearch.xml
            /template
               /catalogsearch
                  template files (PHTML)
/etc
   /modules
      Mage_CatalogSearch.xml
/locale
   /en_US
      Mage_CatalogSearch.csv (localization file)
Figure 3. The CatalogSearch module (from /CatalogSearch)

/Block
   Block classes (PHP)
/controller
   Controllers (PHP)
/etc
   Module configuration (XML)
/Model
   Model classes (PHP)
/Helper
   Helpers (PHP)
With files in so many places, it can be confusing trying to find the right file to work on. The best way to get a handle on that problem is to understand what data is in each location and why it’s put there. A module contains the following data:

Block Classes

   PHP Classes which gather data from Models and Helpers and give it to templates.

Controllers

   PHP Classes which define the pages that are available in a module and load the layout for those pages.

Helpers

   PHP Classes which contain common functions needed to retrieve or transform data in the module.

Layout File

   XML File that tells the controller which blocks to use.

Localization File

   CSV file that defines translations for text to allow multiple languages for a module.

Model Classes

   PHP Classes which retrieve data from other sources (like the database) and transform it using business logic.

Module Configuration

   XML file(s) which hook into Magento functionality to define and enable the module.

Module Specification

   XML File which describes module version and its dependencies on other modules.

Template Files

   PHTML files which take data from blocks and output HTML.

We’ll cover how Magento loads a page in more detail later.

Skins, Layouts and Templates

There is a lot of confusion over the terminology used for parts of a Magento design. If you’re used to splicing PDFs and putting the entire HTML in one place, you’ll need to adjust your thought process in order to understand Magento. What we think of as the program interface is known in Magento as a theme, which can be changed or switched out to provide a different user interface during development, or even while running the store. Using themes, it’s possible to create a holiday version of your website and display it to users only during a certain date range. You can also create multiple stores for different purposes and give each one a particular theme.

There are three parts to every theme, some of which we’ve already defined:

Skin

CSS, JS and image files used to style the site.

Layout

XML layout files collected from each module, used to generate blocks.

Templates

PHTML files from each module used to generate actual XHTML output.


So, magento uses layouts to determine which blocks will render templates. Then, the HTML that those templates render is output to a browser and formatted using the CSS, images and Javascript kept in the skin folder.

Magento Page Request Flow


Conclusion
Take a look through your Magento installation and try to identify all the different pieces that go into a page. Later, we’ll define the actual process of building a page, which should help you understand where everything fits. For now, try to use the right vocabulary for each concept and you’ll be on the right track.

Monday, 3 October 2011

Import/Export in Magento


The import/export tool is very useful within Magento. Basically you can use the import/export tool to do mass imports of products. It makes it much easier if you would like to add 50 products all at once, you would just create a csv or xml file with the matching fields for the database, add your information and then use the import tool to import the products. You can retrieve a sample csv or xml file, but doing an export.

Doing an export is very easy, and allows you to export all of your products out of your website. You might want to do this, if you are moving your website or need to reinstall or upgrade your website, and need to get the products out.

Magento went one or more steps further than most systems. Effectively any import or export is a conversion. From one medium to another. From database to local file, from FTP server to database, from parsed HTML page to Excel spreadsheet, from Google Spreadsheet to catalog.

Basically, it boils down to loading data from one resource, applying unlimited alterations/reformatting, and saving it to another resource.
Welcome to the world of conversion.

Import/Export Concept
The logical steps are:
  • Load records from database
  • Convert internal identificators into human understandable text
  • Map database fields to our custom file headings (sku ⇒ Part Number)
  • Format data array as Excel XML
  • Save resulting text as local or remote file
This sequence of actions we call a Profile.
Here we have 4 categories of components:
  • Adapter (input/output)
  • Mapper (data value processing)
  • Parser (data format conversion)
  • Validator (data validation)
Adapters
Adapters are anything that can plug in to external resource. This may include:
  • Local files
  • FTP, SFTP servers
  • Database table
  • Soap services
  • Standard input/output
  • HTTP interface
  • HTML source
  • Google Spreadsheets
  • Custom resources (specialized db interface, cache repository, etc.)
Adapters can have 2 methods:
  • load – extract data from resource into internal container.
  • save – save data into resource.
Mappers
Mappers are for processing data without changing it’s format or structure. They’re useful for tasks such as mapping one field to another or apply formulas on values.
Mappers can run one method: map
Parsers
Parsers are for changing format of data. Examples:
  • CSV text ⇒ Grid array
  • Excel XML text ⇒ Grid array
  • Grid array ⇒ Product model collection
Parsers can have 2 methods:
  • parse – usually convert from more human readable data to machine friendly format
  • unparse – the opposite, into human readable format
You might notice that Parsers are separated from Adapters, when usually they are associated as one thing (export to CSV file).

Validators
Validators are created to make sure that conditions are met. The conditions can be applied to processed data or environment variables.
Validators can only validate