Thursday, July 28, 2016

Design Patterns Maegnto

Design Patterns Found In Magento in details
  1. Model View Controller Pattern
Model View Controller, MVC for short, is a design pattern where business, presentation and coupling logic are separated. Magento heavily utilizes XML as templating-logic and HTML mixed with PHP files for its views. Models are backed by Varien’s ORM. Most business logic happens in the models whereas the controllers map the model-data to the views.
Because Magento its views are “fat” – they often contain a lot of logic – its not rare that views have an additional PHP class (the Block system) which will help with rendering.
  1. Front Controller Pattern
The front controller pattern makes sure that there is one and only one point of entry. All requests are investigated, routed to the designated controller and then processed accordingly to the specification. The front controller is responsible of initializing the environment and routing requests to designated controllers.
Magento has only one point of entry (index.php) which will initialize the application environment (Mage::app()) and route the request to the correct controller.
  1. Factory Pattern
As implied by the name, the factory pattern is responsible of factorizing (instantiating) classes. It’s widely used through the Magento code base and leverages the autoloading system in Magento. By defining an alias in a module its config.xml you are letting the factory know where it can find classes.
There are various factory-helper methods in the Mage core class and one of them is getModel(). It accepts an alias for a class and will then return an instance of it. Instead of having include calls scattered through the code base, the factory pattern will instantiate classes in an uniform way.
  1. Singleton Pattern
Another way to retrieve an instance of a class, is to call Mage::getSingleton(). It accepts a class alias and before returning an instance, it checks the internal registry whether this class has already been instantiated before – this results in a shared instance. An example of where this is mandatory, is the session storage which should be shared through the code base instead of creating it anew every time.
  1. Registry Pattern
All the singletons are stored in the internal registry: a global scoped container for storing data. It is not only for internal use. The Mage::register($key, $value), ::registry($key) and ::unregister($key) methods can be respectively used for storing, retrieving and removing data from the registry. The registry is often used for transferring data between scopes when they cannot be passed on, otherwise.
  1. Prototype Pattern
Where the factory pattern (#3 on our list) stops, is where the prototype pattern continues. It defines that instances of classes can retrieve a specific other class instance depending on its parent class (the prototype). A notable example is the Mage_Catalog_Model_Product class which has a getTypeInstance method to retrieve the specific Mage_Catalog_Model_Product_Type with a specific subset of methods and properties not applicable to all products.
For example, the Mage_Downloadable_Model_Product_Type ultimately extends the Mage_Catalog_Model_Product_Type. If you are iterating over an order and want to call a specific method of a downloadable product, you will need to factorize it first with the getTypeInstance method of the original product.
  1. Object Pool Pattern
The object pool pattern is simply a box with objects so that they do not have to be allocated and destroyed over and over again. It’s not used a lot in Magento other than for heavy tasks where resources can get limited soon, like importing products. The object pool (managed by Varien_Object_Cache) can be accessed with Mage::objects().
  1. Iterator Pattern
The iterator pattern defines that there is a shared way to iterate over a container with objects. In Magento, this is handled by the Varien_Data_Collection which on its turn uses various baked-in PHP classes (like ArrayIterator) for having a more OO-interface to arrays. This ensures that model-collections will always have a common API to iterate over without being dependent of the actual models.
  1. Lazy Loading Pattern
Lazy loading ensures that loading data is delayed until the point when it is actually needed. This results in less resources being used. One of the lazy loading behaviors of Magento is that of collections. If you were to retrieve a collection of products with Mage::getModel('catalog/product')->getCollection(), the database will only be touched when you actually access the collection by, for example, iterating over it or retrieving the count of models found.
  1. Service Locator Pattern
The service locator pattern abstracts away the retrieval of a certain service. This allows for changing the service without breaking anything (as it adheres to its abstract foundation) but also fetching the service as seen fit for its purpose.
Ryan exemplifies this with database connections. Another example is that of Magento its caching mechanism where Mage::getCache() is a service locator by-proxy for the cache storage supplied by Zend or other vendors.
  1. Module Pattern
Anyone familiar with Magento development has stumbled upon the module pattern. It basically defines that different domains are grouped into separate modules which function independent of each other and can be plugged-in to the main system as deemed appropriate. In an ideal situation, an implementation of the module pattern would make sure that each element can be removed or swapped. One of the protagonists of the module pattern in PHP is the Composer package manager.
Though Magento heavily relies on a modular architecture, its not modular to the bone. Certain functionality is heavily tied to the core and can not be easily changed. There is also the heavy usage of the super-global Mage core-class which introduces all sorts of system-wide dependencies not easily overseen.
  1. Observer Pattern
Magento its event-driven architecture is a result of an implementation of the observer pattern. By defining observers (or listeners), extra code can be hooked which will be called upon as the observed event fires. Magento uses its XML-data storage to define observers. If an event is fired with Mage::dispatchEvent($eventName, $data), the data storage will be consulted and the appropriate observers for $event will be fired.

Wednesday, July 27, 2016

related product by sales

    public function getItems()
    {
        $bySale = 'SELECT count(*) as total,product_id FROM '.$tablePrefix.'`sales_flat_order_item` WHERE order_id IN (select order_id from '.$tablePrefix.'`sales_flat_order_item` where product_id = '.$productId.') and product_id != '.$productId.' group by product_id order by total desc';
        $product = Mage::registry('product');
        $productId = $product->getEntityId();
       
        $orderItems = Mage::getModel('sales/order_item')->getCollection()
                ->addAttributeToSelect('order_id')
                ->addFieldToFilter('product_id', $productId)
                ->load();
        $orderIds = array();
        foreach ($orderItems as $orderItem)
        {
            $orderIds[] = $orderItem->getOrderId();
        }
       
        $saleItems = Mage::getModel('sales/order_item')->getCollection()
                ->addAttributeToSelect('product_id')
                ->addFieldToFilter('order_id',array('in' => $orderIds))
                ->addFieldToFilter('product_id',array('neq'=>$productId));
        $saleItems->getSelect()->columns('COUNT(*) as total')->Group('product_id')->Order('total','DESC');
        $productIds = array();
        foreach ($saleItems as $saleItem)
        {
            $productIds[] = $saleItem->getProductId();
        }
       
        //echo($saleItems->getSelect());
        //var_dump($productIds);
        //exit;
       
        $existingItems = $this->_itemCollection->getItems();
        foreach ($productIds as $productId)
        {
            $productHelper = Mage::helper('catalog/product');
            // Standard algorithm to prepare and rendern product view page
            $product = Mage::getModel('catalog/product')
                ->setStoreId(Mage::app()->getStore()->getId())
                ->load($productId);
            if (!$product) {
                //throw new Mage_Core_Exception($this->__('Product is not loaded'), $this->ERR_NO_PRODUCT_LOADED);
            }
            else
            {
                //var_dump($product);exit;
                //var_dump($existingItems);exit;
                if (!$productHelper->canShow($product)) {
                    continue;
                }
                if (!in_array(Mage::app()->getStore()->getWebsiteId(), $product->getWebsiteIds())) {
                    continue;
                }
                if(!in_array($product, $existingItems))
                {
                    $this->_itemCollection->addItem($product);
                    //var_dump($existingItems);
                    //exit();
                }
            }
        }
        return $this->_itemCollection;
    }

mysql raw query

        $query = 'SELECT count(*) as total,product_id FROM '.$tablePrefix.'`sales_flat_order_item` WHERE order_id IN (select order_id from '.$tablePrefix.'`sales_flat_order_item` where product_id = '.$productId.') and product_id != '.$productId.' group by product_id order by total desc';
       
        $xml = simplexml_load_file('app/etc/local.xml');
        $host = $xml->global->resources->default_setup->connection->host;
        $username = $xml->global->resources->default_setup->connection->username;
        $password = $xml->global->resources->default_setup->connection->password;
        $dbname = $xml->global->resources->default_setup->connection->dbname;
        $res = mysql_pconnect($host, $username, $password);  
        mysql_select_db($dbname);
        $productIds = mysql_query($query) or die(mysql_error());

        while($fetch = mysql_fetch_array($productIds))
        {}

Tuesday, July 26, 2016

enable tag in magento 1.9 rwd theme

You are using the RWD theme which does not include Product Tags by default. Here's how to add them to the RWD theme:
Step 1: Copy the tags template files to your theme -go to app/design/frontend/base/default/template/tag -Copy the entire /tag folder to: -app/design/frontend/rwd/default/template note that you may have a custom package instead of 'rwd' and you should have a custom theme name instead of 'default'
Step 2: Add the XML call to your layout open app/design/frontend/rwd/default/layout/tag.xmlchange the following code from:
<!-- Remove all tags functionality from theme layout -->
to:
 <catalog_product_view translate="label">
     <label>Catalog Product View</label>
      <!-- Mage_Tag -->
     <reference name="product.info.additional">
         <block type="tag/product_list" name="product_tag_list" before="-" template="tag/list.phtml">
             <block type="page/html_wrapper" name="product.tag.list.list.before" as="list_before"
 translate="label">
                 <label>Tags List Before</label>
                 <action method="setMayBeInvisible"><value>1</value></action>
             </block>
         </block>
     </reference> 
  </catalog_product_view>
*note that you may have a custom package instead of 'rwd' and you should have a custom theme name instead of 'default'
If you don't know which package/theme you are using you can check in the admin under System->Configuration->Design(left column)->Package(tab) & Theme(tab).
You may need to flush you Magento caches to see the changes. In the admin go to System->Cache Management and flush all Magento caches. Now refresh your website and you should see the tags show up near the bottom of the page below the Upsell Products.

Log Queries



            <default_setup>
                <connection>
                    <host><![CDATA[localhost]]></host>
                    <username><![CDATA[root]]></username>
                    <password><![CDATA[]]></password>
                    <dbname><![CDATA[magento7]]></dbname>
                    <initStatements><![CDATA[SET NAMES utf8]]></initStatements>
                    <model><![CDATA[mysql4]]></model>
                    <type><![CDATA[pdo_mysql]]></type>
                    <pdoType><![CDATA[]]></pdoType>
                    <active>1</active>
                    <profiler>1</profiler>
                </connection>
            </default_setup>

add <profiler>1 at the local.xml in app/etc/

and add the following lines in index.php file at the last,

//get all queries
$profiler = Mage::getSingleton('core/resource')->getConnection('core_write')->getProfiler();
Mage::log(print_r($profiler->getQueryProfiles(), true), null, 'queries.log', true);

Tuesday, July 19, 2016

get all events name in maegnto

Mage::log($name, null, 'events.log', true);
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <meta charset="UTF-8"> <title>Events file logger</title> </head> <body> <?php $lines = file($_GET['file_path']); foreach($lines as $lineNumber => $lineContent) { $eventName = explode('):', $lineContent); $events[] = $eventName[1]; } $events = array_values(array_unique($events)); foreach ($events as $key => $event) { echo "{$key}.{$event}</br>"; } ?> </body> </html>
and access like
localhost/poc/magento/events_reader.php?file_path=E:\wamp\www\magento\var\log\events.log

Monday, July 18, 2016

code font family

code {
  background-color:#EEEEEE;
  font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New;
}

Monday, July 4, 2016

Magento. How to manage CSV files translations

In order to do that, you just need to create translate.csv in app/design/frontend/default/themexxx/locale/languagecode_COUNTRYCODE and put your translated strings inside this translate.csv file. Some templates may already contain the locales for some languages. You can edit the file via FTPmanager (TotalCommaner, FileZilla, etc.) or Hosting Control panel File manager:
magento_how_to_manage_csv_translations1
NOTE: We recommend disabling Magento cache or clearing it after all configuration changes. Please check the following tutorial for the detailed guidance Magento. How to clear cache .
To perform CSV translations, you need to note the following:
  1. All strings should start and end with double quotes and should be separated with comma (,), not a semicolon or any other sign. For instance:
      "Default line","Translated line" 
  2. You can alternate the default theme strings with the help of app/design/frontend/default/themexxx/locale/en_US/translate.csv file. For example:
     "My Cart","My Basket"
  3. All the lines are case-sensitive and the first message must be copied exactly as it appears in the default en_US version. For example, if in en_USlocale the string looks like that:
    "%s Item(s)","%s Item(s)" 
    “%s Items”, “%s item(s)”, etc. wouldn’t work.
  4. Some strings can contain %1$s %s %d etc., and if you want to have the correct strings in your translations, these entries should be also kept in the translated string.
     "%s Item(s)","%s Product(s)" 
  5. Your text editor should be able to save an edit CSV file in UTF-8 encoding (), especially when you translate using different alphabets. If you have your translations in Excel, you need to convert your file to UTF-8 (find more info on how to convert Excel to CSV with UTF-8 encoding).
  6. If you need to have double quotes in your string, they need to be escaped by using two double quotes:
     "Warning!","Attention!" 
  7. There are some strings that can be presented in a few extensions simultaneously. For example, in “Add To Cart” strings can be found in both Mage_Catalog.csv and Mage_Checkout.csv. To solve this issue with translate.csv, put your extension name as a prefix and you will be able to translate them separately.
     "Mage_Catalog::Add to Cart","Add to Basket"
     "Mage_Checkout::Add to Cart","Add to my shopping cart"
  8. Click Save changes button to confirm the changes:
    magento_how_to_manage_csv_translations2
  9. Go back to your website and refresh the page to see changes.
That is the end of the tutorial. Now you know how to manage CSV translations in Magento templates.
courtesy : http://www.templatemonster.com/help/magento-how-to-manage-csv-files-translations.html#gref

Magento : Get Base Url , Skin Url , Media Url , Js Url , Store Url and Current Url

Get Url in phtml files

1. Get Base Url :
Mage::getBaseUrl();
2. Get Skin Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
(a) Unsecure Skin Url :
$this->getSkinUrl('images/imagename.jpg');
(b) Secure Skin Url :
$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));
3. Get Media Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
4. Get Js Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
5. Get Store Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
6. Get Current Url
Mage::helper('core/url')->getCurrentUrl();

Get Url in cms pages or static blocks

1. Get Base Url :
{{store url=""}}
2. Get Skin Url :
{{skin url='images/imagename.jpg'}}
3. Get Media Url :
{{media url='/imagename.jpg'}}
4. Get Store Url :
{{store url='mypage.html'}}