Environment specific configuration in zend


In software development life cycle, we generally need different type of environments for different purpose like – “development”, “testing”, “production” etc.

And all these environments has some environment specific configuration. like in development server “display error” will be on and payment mode will be “testmode” But in production server “display error” will be off and payment mode will be “livemode” In production server error logging will be on but in testing server it may not be on. Database connection will be different for each environment. etc etc…

Problem:

Its been a big headache to server management team to modify configuration files each time code update to any server.
Here we have created multiple configuration files for each server and automatically loaded environment wise configuration file using “zend-framework”.

Solution:

Here we will consider 3 environment- “Production”, “QA” and “Development” in order to explain the process.
So we will create 4 ini files:
common_config.ini: to keep common configuration (which don’t change with environments)
app_prod.ini: “Production” server specific configuration
app_QA.ini: “QA” server specific configuration
app_dev.ini: “Development” server specific configuration

common_config.ini:

[Production]
phpSettings.error_log = [path to file] "/application.log"

includePaths.application = APP_PATH
includePaths.library = APP_LIB

bootstrap.path = [path to file] "/Bootstrap.php"
bootstrap.class = "Project_Bootstrap"

autoloadernamespaces.0 = "Project"

resources.frontController.moduleControllerDirectoryName = "controllers"
resources.frontController.moduleDirectory = [path to file] "/modules"

resources.frontController.defaultControllerName = "index"
resources.frontController.defaultAction = "index"
resources.frontController.defaultModule = "account"
[QA : Production]
[Development : Production]

Look at last 2 lines- it is saying QA and Development server both will extend configuration from Production.

app_prod.ini:

[Production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
phpSettings.log_errors = 1

;payment related credentials
payment.mode = "liveMode"
;db configuration
resources.db.adapter = "Pdo_Mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "user1"
resources.db.params.password = "pass1"
resources.db.params.dbname = "db_prod"

app_QA.ini:

[QA]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
phpSettings.log_errors = 1

;payment related credentials
payment.mode = "testMode"
;db configuration
resources.db.adapter = "Pdo_Mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "user2"
resources.db.params.password = "pass2"
resources.db.params.dbname = "db_qa"

app_dev.ini:

Similar to QA. you now know what will be in this configuration file. 🙂

So we made ready all configuration files. Now need to load proper configuration for environments.
index.php file will contain something like this:

 

defined('COMMON_CONFIG_INI_PATH') || define('COMMON_CONFIG_INI_PATH',
        [path to file] . '/Config/common_config.ini');

// set APP_INI_PATH according to environment
switch (APP_ENV) {
    case 'Production' :
        defined('APP_INI_PATH') || define('APP_INI_PATH',
            [path to file] . '/Config/app_prod.ini');
        break;
    case 'QA' :
        defined('APP_INI_PATH') || define('APP_INI_PATH',
            [path to file] . '/Config/app_QA.ini');
        break;
    case 'Development' :
        defined('APP_INI_PATH') || define('APP_INI_PATH',
            [path to file] . '/Config/app_dev.ini');
}

defined('APP_LOG_PATH') || define('APP_LOG_PATH',
        realpath(dirname(__FILE__) . '/../logs'));

//Bootstrap the application
require_once('Zend/Application.php');
//load zend_app with config file and run
$application = new Zend_Application(APP_ENV,
        array(
            'config' => array(
                        COMMON_CONFIG_INI_PATH,
                        APP_INI_PATH
                       )
             )
    );
$application->bootstrap()->run();

So here we we have set 2 constant for configuration files according to environment: COMMON_CONFIG_INI_PATH and APP_INI_PATH
and loaded these 2 configuration while bootstrapping.

You are done. Nothing more. Simple, isn’t it? 🙂

Advertisements

Performance Issue in three.js while creating large number of objects and its solution


Few days back I am creating a demo using three.js library(used for rendering 3D objects). I have added three to four geometry on the scene. It was working just fine as well with animation added to it. But when I have increased the number of the geometry rendered on the scene, performance of the demo decreased significantly. 😦

Page loading time also increased. I have done a small mistake in my codding, and many of us can face same issue sometime, so thought of sharing to save your time.. 🙂

For example lets say I need to create five cylinders on the scene, The code I have written:

for ( var i = 1; i < 6; i ++ ) {
var cylinderOne = new THREE.CylinderGeometry(14, 14, 120, 25, 25, false);
var cylinder = new THREE.Mesh(cylinderOne, new THREE.MeshNormalMaterial());
cylinder.position.x = 10*i;
scene.add(cylinder);
}

In the above code it is adding five cylinders to the scene. The issue in the code is in the following line:
var cylinderOne = new THREE.CylinderGeometry(14, 14, 120, 25, 25, false);
This line is creating the cylinder object. In the above code we have added this line inside the for loop. So it is creating as many number of objects as we want to render on the scene which increases the page load time.

We ca decrease the page load time significantly just by adding creating the object outside the loop, which will create only one object for one geometry and we can reuse the same object as many times to as we want to render on the scene as follows :

var cylinderOne = new THREE.CylinderGeometry(14, 14, 120, 25, 25, false);
for ( var i = 1; i < 6; i ++ ) {
var cylinder = new THREE.Mesh(cylinderOne, new THREE.MeshNormalMaterial());
cylinder.position.x = 10*i;
scene.add(cylinder);
}

Thats it, 🙂 it will increase your page load time…

CONSTRUCTOR and DesTruCtoR in php


As a developer “Constructor” is very common to us and we use it very frequently. But do we know what is destructor and when to use it?

Yes the names describe their meanings themselves. Constructor and destructor are 2 methods of a class which are called at the time of object construction and destruction respectively.

Constructor:

How to create:

Generally the way of creating a constructor is creating a method, name of which is same as class name.

For Example:

class foo {
    function foo()
    {
        // PHP 4 style constructor
    }
}

Whereas PHP5 introduce a new magic method “__construct()” to declare a constructor.

The benefit of this method is if sometime we need to change the name of class, we don’t need to change the name of constructor.

For Example:

class newFoo {
    function __construct()
    {
        // PHP 5+ style constructor
    }
}

PHP5 first searches for magic method style constructor. If not present, it searches for a method, same name with class name. So, both style works.

Why to use:

Constructors are useful for initializing an object’s properties, or for performing startup procedures. For example, need to connect to database or set some specific set of configuration or fetch some remote file and cache it for quick usage.

Destructor:

How to create:

PHP 5 introduces a destructor concept similar to OOP concept. Magic method “__destruct()” is used to declare a destructor.

For Example:

class foo {
    function __construct()
    {
        echo ‘Constructor called’. PHP_EOL;
    }
    function __destruct()
    {
        echo ‘Destructor called’;
    }
}
new foo();

This code will display:

Constructor called
Destructor called

REMEMBER that destructor will not be called till the last reference of the object is gone, and this may not take place when you want or expect it.

For Example:

$obj1 = new foo();
$obj2 = $obj1;
unset($obj1);

This one will not call destructor as even if $obj1 is getting unset, another reference is still present.

Why to use:

Its mainly useful for performing cleanup procedures, such as disconnect remote connection, remove temporary files etc.

Hope this will help to effectively use constructor and destructor. 🙂

 

References:
http://php.net/manual/en/language.oop5.decon.php
http://www-numi.fnal.gov

MyISAM vs InnoDB….??


Storage Engines are the programs that are integrated with a MYSQL database management to manage the data tables. MYSQL supports different storage engines that handles different tables.

Selection of Storage Engine:

Selection of storage engine, depends on users table type and its purpose. Each has their own advantages and disadvantages. Also, possible to select engine at the time of creating tables.
While selecting storage engine, the factors that can affect your selection are:

  • Transaction and concurrency
  • Backups
  • Special features

You should use INNODB for your tables unless you have a compelling need to use a different engine!! (To get High Performance)

By- Peter Zaitsev

Some of important Storage Engines are :
MyISAM, INNODB, MERGE, MEMORY, etc.

The major thing that one should know what are the difference between InnoDB and MyISAM???

MyISAM

(+)

  • Designed with a thinking that database are frequently read not updated.
  • Simple to understand and implement.
  • Has full text searching capability.
  • Good for frequent read operations(when several computations are executing simultaneously)
  • Faster reads and writes for small to medium sized tables.
  • Lock tables while updating.
  • Count(*) queries are fast

(-)

  • Non-transactional. Data loss issues during crashes.
  • Table level locking
  • Insert and update queries are scaleable, concurrency issues

InnoDB

(+)

  • Designed with a thinking that database are frequently updated not read.
  • Transaction-safe
  • Data-integrity is maintained throughout the entire query process.
  • Clustering by primary key for faster lookups and ordering.
  • Transactional, crash-safe, better online backup capability.
  • Allow multiple updates on single table
  • Locks only row, not table.

(-)

  • Slower writes(insert, update queries)
  • Slower BLOB handling
  • Count(*) queries require full table scan.

Simple comparison chart

MyISAM InnoDB
Required full text Search Yes 5.6+
Require Transactions Yes
Frequent select queries Yes
Frequent insert,update,delete Yes
Row Locking (multi processing on single table) Yes
Relational base design Yes

 

Summary:

Frequent reading, almost no writing => MyISAM
Full text search in MySQL <= 5.5 => MyISAM

In all other circumstances, InnoDB is usually the best way to go and INNODB can now use Sphinx for Full Text Searching.

Reference:

http://www.slideshare.net/gauravpaliwal/mysql-engines
http://en.wikipedia.org/wiki/Comparison_of_MySQL_database_engines

Enjoy Coding! 🙂

 

How to add billing address, shipping address, last 4 digits of CC to global search for Magento backend


Magento backend is having global search functionality,globalSearch
but we can not search few important fields or parameters using global search. 😦
Recently I came across a situation where I need to add many fields to the global search.
After few hours of research, I got the model classes from where it adds the fields to search.

There are three models for customer, product and order, one each.
Path of the files are: 

app/code/core/Mage/Adminhtml/Model/Search/Catalog.php
app/code/core/Mage/Adminhtml/Model/Search/Customer.php
app/code/core/Mage/Adminhtml/Model/Search/Order.php

According to the requirement we can create our custom module in local and overwrite the file(model) over there. From the local we can modify the content of the file to add billing address, shipping address, last 4 digits of CC to global search.

The path of local file:

app/code/local/MyModule/Adminhtml/Model/Search/Catalog.php
app/code/local/MyModule/Adminhtml/Model/Search/Customer.php
app/code/local/MyModule/Adminhtml/Model/Search/Order.php

Note: “MyModule”  is my custom module name in local code pool.
Here I will explain how we can add different address parameters, order id , last 4 digit of CC, customers name etc. For this we will modify Order.php and Customer.php.

Step:1

On this page : app/code/local/MyModule/Adminhtml/Model/Search/Order.php

 $query = $this->getQuery();
        //TODO: add full name logic
        $collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('*')
            ->addAttributeToSearchFilter(array(
                array('attribute' => 'increment_id',       'like'=>$query.'%'),
                array('attribute' => 'billing_firstname',  'like'=>$query.'%'),
                array('attribute' => 'billing_lastname',   'like'=>$query.'%'),
                array('attribute' => 'billing_telephone',  'like'=>$query.'%'),
                array('attribute' => 'billing_postcode',   'like'=>$query.'%'),

                array('attribute' => 'shipping_firstname', 'like'=>$query.'%'),
                array('attribute' => 'shipping_lastname',  'like'=>$query.'%'),
                array('attribute' => 'shipping_telephone', 'like'=>$query.'%'),
                array('attribute' => 'shipping_postcode',  'like'=>$query.'%'),
            ))
            ->setCurPage($this->getStart())
            ->setPageSize($this->getLimit())
            ->load();

We need to change this snippet of code with following snippet to add order increment_id, billing details, shipping details and last 4 digits of CC.

$query = $this->getQuery();
$salesFlatQuotePayment = (string)Mage::getConfig()->getTablePrefix() . 'sales_flat_quote_payment';
            $collection = Mage::getResourceModel('sales/order_collection')->addAttributeToSelect('*');
            $collection->getSelect()
                       ->joinLeft(array('sales_flat_quote_payment' => $salesFlatQuotePayment),
                       "(sales_flat_quote_payment.quote_id=main_table.quote_id)",array('cc_last4')
            ) ;
            
              $collection= $collection->addAttributeToSearchFilter(array(
                    array('attribute' => 'increment_id',                           'like'=>$query.'%'),
                    array('attribute' => 'entity_id',                              'like'=>$query.'%'),
                    array('attribute' => 'billing_firstname',                      'like'=>$query.'%'),
                    array('attribute' => 'billing_lastname',                       'like'=>$query.'%'),
                    array('attribute' => 'billing_telephone',                      'like'=>$query.'%'),
                    array('attribute' => 'billing_postcode',                       'like'=>$query.'%'),
                    array('attribute' => 'billing_o_a.city',                       'like'=>$query.'%'),
                    array('attribute' => 'billing_o_a.region',                     'like'=>$query.'%'),
                    array('attribute' => 'billing_o_a.street',                     'like'=>$query.'%'),
                    array('attribute' => 'sales_flat_quote_payment.cc_last4',      'like'=>'%'.$query.'%'),

                    array('attribute' => 'shipping_firstname',                     'like'=>$query.'%'),
                    array('attribute' => 'shipping_lastname',                      'like'=>$query.'%'),
                    array('attribute' => 'shipping_telephone',                     'like'=>$query.'%'),
                    array('attribute' => 'shipping_postcode',                      'like'=>$query.'%'),
                    array('attribute' => 'shipping_o_a.city',                      'like'=>$query.'%'),
                    array('attribute' => 'shipping_o_a.region',                    'like'=>$query.'%'),
                    array('attribute' => 'shipping_o_a.street',                    'like'=>$query.'%'),
                ))
                ->setCurPage($this->getStart())
                ->setPageSize($this->getLimit())
                ->load();

By adding this code we will be able to search by order increment_id, billing details, shipping details and last 4 digits of CC.

Step:2

On this page : app/code/local/MyModule/Adminhtml/Model/Search/Customer.php

$collection = Mage::getResourceModel('customer/customer_collection')
            ->addNameToSelect()
            ->joinAttribute('company', 'customer_address/company', 'default_billing', null, 'left')
            ->addAttributeToFilter(array(
                array('attribute'=>'firstname', 'like' => $this->getQuery().'%'),
                array('attribute'=>'lastname', 'like'  => $this->getQuery().'%'),
                array('attribute'=>'company', 'like'   => $this->getQuery().'%'),
            ))
            ->setPage(1, 10)
            ->load();

We need to change this snippet of code with following snippet to add default billing address, customer’s  city, region and street.

$collection = Mage::getResourceModel('customer/customer_collection')
                ->addNameToSelect()
                ->joinAttribute('company', 'customer_address/company', 'default_billing', null, 'left')
                ->joinAttribute('city', 'customer_address/city', 'default_billing', null, 'left')
                ->joinAttribute('region', 'customer_address/region', 'default_billing', null, 'left')
                ->joinAttribute('street', 'customer_address/street', 'default_billing', null, 'left')

                ->addAttributeToFilter(array(
                    array('attribute'=>'firstname', 'like' => $query.'%'),
                    array('attribute'=>'lastname', 'like'  => $query.'%'),
                    array('attribute'=>'company', 'like'   => $query.'%'),
                    array('attribute'=>'city', 'like'      => $query.'%'),
                    array('attribute'=>'region', 'like'    => $query.'%'),
                    array('attribute'=>'street', 'like'    => $query.'%'),
                ))
                ->setPage(1, 10)
                ->load();

Now we can upload these two files and flush the cache. Then from backend search for any field from Global Search… 🙂