OOPS based interview question in PHP


1. What is Object Oriented Programming?

OOPS, a well-known and highly adopted programming language model which revolves around objects, which can have the data and functions. OOPs allows developer to maintain the code easily as it allows to keep similar type of functionality into classes, thus increase code reusability and add an extra layer of security, bind up functionality into a several smaller unit.


2. What are the principle of OOPS? Explain them?

The most frequently and a very popular interview questions for developer, OOPs majorly have 3-4 principles:-
Encapsulation
Wrapping up of data members and methods/function into a single unit i.e., in a class is known as encapsulation. It means hiding internal details of an object by using access specifier, thus adding a level of restriction to data members and function so that others objects cannot access them.

Abstraction
It hides the unnecessary data and show only the relevant information. We create abstract class and function in PHP to achieve abstraction.

Polymorphism
It means a same name function can have many forms or can behave differently in different situation. It is of two type; run time polymorphism i.e, overriding and compile tile polymorphism i.e, overloading. PHP does not have overloading similar to other OOPS languages. It achieve overloading by magic methods.

Inheritance
It provides code reusability, by allowing the child class to inherit the functions from parent class rather than writing it again and again. In PHP we extends classes by using extends keywords.

3. What is the purpose of a constructor?
A constructor is a magic method in PHP which is called automatically during initialization of an object. Constructors are used to assign default value or to perform any action which we want to do on a creation of an object. In PHP constructor is created in following way:-

function __construct(){}

Note: – Unlike other languages constructor in PHP are not created with the class name.

4. What is difference between abstract and interface?
Abstract class may or may not have abstract method, it can also have concrete method but in case of interface all methods are defined as abstract no concrete method is allowed. Interface is used to achieve multiple level inheritance.

5. What is Polymorphism? Does PHP support overloading?
Review answer of question 2 for this.

6. What is difference between abstraction and inheritance?
Both abstraction and encapsulation hides the information but in case of encapsulation it solves problem at implementation level, thus hiding the internal details of object i.e, how object does something, how its method and data member are interacting While abstraction solves problem at design level, it hides only the unwanted data and gives all relevant data such as outer look of a car, allowing you to use steering but did not know how it’s actually working.

7. What are magic methods?
Magic methods are special method in php that start with double underscore and convey special meaning to compiler, they are never called explicility. They are called implicility whenever needed. Such as __construct is always called automatically when an object of class is created.

8. How to call parent constructor in php?
parent::__construct() is used to call parent class constructor.

9. What are access modifiers?
Public, protected and private are the keywords used as access modifiers to set the visibility for functions and data members. Public members are accessible everywhere, protected are accessible only within the class itself or by inheriting class.

10. What is Scope Resolution Operator?
This operator refer to the scope of some blocks, and is used to access properties and method of classes. Mainly we use it to access static variables and method.

11. What is Static Keyword in PHP?
We make class properties and methods as static to access them without instantiating the class. They cannot be accessed with an instantiated class objects. Static keyword is also used for late static binding.

12. What is late static binding?
Late static binding is used to refer a class that was used at runtime, we use static keyword for this. Let’s understand it with an example:-

<?php
    class Car
    {
        public static function run()
        {
            return static::getName();
        }

        private static function getName()
        {
            return 'Car';
        }
    }

    class Toyota extends Car
    {
        public static function getName()
        {
            return 'Toyota';
        }
    }

    echo Car::run(); // Output: Car, Here we are calling run function by referring car class. And run function calls getName with static keyword that means class car run function will be used.
    echo Toyota::run(); // Output: Toyota, Here we are calling run function by referring toyota class. And run function calls getName with static keyword that means class toyota run function will be used.
?>

Thus in above example you can see that late static binding works by storing a class name in the last “non-forwarding call”.

13. What are Traits in PHP?
PHP only supports single inheritance i.e, a class can only inherit one other class. However, sometimes we need to inherit multiple classes.
Therefore PHP 5.4 introduces Traits, that reduce some limitations of single inheritance by allowing a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. Traits cannot be instantiated.
Below is the code explaining traits implementation:-

class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();

The above example will output:- Hello World!

14. What is Object Iteration?
It is possible to iterate through an object in PHP 5 through a list of items, for example by using a foreach statement. By default, all visible properties will be used for the iteration.

15. What is Final Keyword in PHP?
We use final keyword to prevents child classes from overriding a method or to prevent class itself from overriding.
For example,

class ABC{
   final function xyz(){}
}
xyz is set final which means it cannot we overridden in any other class.

16. Can we make a constructor as private?
Yes, we can, it is generally a common practice for Singleton Pattern. Making constructor as private ensures that there can be only one instance of a Class and provides a global access point to that instance.

17. What is serialization?
PHP provides an option for object serialization. We use serialize() function that returns a string containing a byte-stream representation of any value that can be stored in PHP and unserialize() function for vice-versa. For example:-

Suppose I have code:-
$serialized_data = serialize(array('Math', 'Language', 'Science'));
echo  $serialized_data;

Then the output of above code is a:3:{i:0;s:4:"Math";i:1;s:8:"Language";i:2;s:7:"Science";}

Magento Interview Question Part-3

Another version of Magento interview question:-

1. what are the different order states in Magento?
Magento has following order states :-
Pending: – Whenever we create place any order in Magento then it is marked in pending status, which means that order has not been processed yet.
Pending PayPal: Those order which did not clear by PayPal has this status.
Processing: Processing means that orders have either been invoiced or shipped, but not both.
Complete: When an order have been invoiced and have shipped then it is marked as complete.
Canceled: If an order is canceled from admin section.
Closed: When an order have had a credit memo assigned to it and the customer has been refunded for their order then it is marked as closed order.
On Hold: Orders placed on hold must be taken off hold before continuing any further actions.

Order states are defined in Mage_Sales_Model_Order:
const STATE_NEW = ‘new’;
const STATE_PENDING_PAYMENT = ‘pending_payment’;
const STATE_PROCESSING = ‘processing’;
const STATE_COMPLETE = ‘complete’;
const STATE_CLOSED = ‘closed’;
const STATE_CANCELED = ‘canceled’;
const STATE_HOLDED = ‘holded’;
const STATE_PAYMENT_REVIEW = ‘payment_review’;

2. what is the difference between order status and order state Magento?
Order state and Order status are usually mixed up because their names and functions are quite similar. An order state is a position of an order in an order processing flow. Each Magento order status can be assigned to more than one order state.
For example, a “Pending Payment” order state can have the following order statuses:
Pending Payment Paypal
Pending Payment Card
Pending Payment Store Credit
and so on…

3. Mention what is the limitation of Magento?
We all know about the advantage of our Magento but let’s go through limitation also:-
Magento runs on PHP, thus it takes up a lot of memory during processes and strong hardware is required to run the software.
Magento is quite complex for admin users and for developers too.
The most important are slowness, every Magento developer has to go through this, a good server configuration and optimized code are needed for using Magento.

4. Explain how Magento can be made more secure for the client?
Below are some points that will make our Magento application more secure:-
– We should use a strong password and should change them at regular interval.
– We should update all Magento security patches.
– We should disable remote access to Magento Connect Manager
– We should disable Downloader on production sites
– We can also restrict access to safe IP addresses

5. Explain how you can move Magento to another Directory OR can move the Magento to the Production environment?
– Firstly, you need to zip your code and dump SQL database.
– Upload and extract zip content and create a database on the server and import the data from SQL dump.
– Edit app/etc/local.xml to change the database name, user, and password to match your new database.
– In your new database, go to the core_config_data table, and change the web/unsecure/base_url and web/secure/base_url to the URL of your development server. Don’t forget a forward slash at the end of the URL.
– Delete cache and session in the var folder on your dev server. Your application should start working now.

6. How do we upgrade Magento version?
Firstly make sure to take a backup of current database and code. And place maintenance.flag file on root so that website is offline.
– Remove all file and folder from old version and replace them with new version except maintenance.flag
– Download latest Magento from the http://www.magentocommerce.com/download
– Now from your older Magento version merge your following custom folders into the new version
Community app/code/community
Local app/code/local
Media
your theme or package
custom folders from Skin (both for adminhtml and frontend).
copy your custom XML files from app/etc/modules/ to current app/etc/modules/
any custom admin theme folder from adminhtml/default/yourtheme.
copy your custom folders from adminhtml/default/default/ from old application to adminhtml/default/default/ of new Magento version.
custom js files if any from app/js/.
– Now go to app/etc/local.xml.Edit database details them; put your database username and password and database name.
– Remove maintenance.flag file and check the site in the browser. it is done.

7. How can we change the admin default URL by using some custom name?
You can simply change it in local.xml file. Inside frontname node:-

<admin>
   <routers>
      <adminhtml>
        <args>
            <frontName><![CDATA[adminnewpath]]></frontName>
        </args>
    </adminhtml>
</routers>

8. What is the benefit of using namespace (package) in magento?
Magento has several module and they might have same name, thus to differentiate them we have a namespace which we keep unique.

9. How to add an external javascript file to Magento?
To add external JS use below sample code:-

<reference name="head">
   <block type="core/text" name="google.cdn.jquery">
      <action method="setText">
        <text>
           script details
        </text>
      </action>
   </block>
</reference>

10. What are handles in Magento (layout)?
For every request in Magento, we have a handle which is created as per the controller called. In layout file of theme, we can list our XML code which will be specific to that controller. There are some handles that are called on every page such as default.

Magento Interview Question Part-2

Some more questions to go:-

1. What is EAV model? How Magento uses EAV Model?

EAV basically stands for Entity Attribute Value. I will be explaining it with an example in terms of Magento, considering the product as an Entity. We can have a various attribute for a product i.e, various column in which product related data will be stored, for example, color, product name, size, product description, length, weight etc. Now Magento manages lots of product and it is always a possibility that each type of product might not require all columns to have a value such as, if we are selling a banana then length is not needed for that, So the whole column will always be empty which will simply make our space as non-utilized. Also if we have 1000 types of product and then in total they will be using lots of columns and thus make our table very huge. So in EAV, we break the things and attribute/column are maintained as a row. Here we are mainly normalizing our tables.
Now as per Magento we have table eav_entity, which list all entity type. Eav_Attribute which has attribute/column data. And further on basis of entity and their datatype we have tables which save their value.
Thus, in short, The most widely used way to store entities is implementing attributes as columns and entities as rows.

2. List the different type of product that Magento has and mentioned when to use which one?

Simple Product:-
It is the most basic type of physical product. For example:-
I want to sell a shirt with Small size.Each simple product has a unique SKU.

Configurable Product:-
In these we provide a different option for a simple product, this allows you to select any one of those options and order. For example:-
We have a configurable product, shirt with different size such as s, m, xs, xl and color white, black, gray. This as a whole is configurable and, in admin, they all are the different simple product such as a shirt with size m and a color black. The configurable product basically ties them all together and gives the end user the choice, usually from a drop-down menu to select whichever product he wants.

Grouped Product:-
It is a “group” of simple products so that combo or several associated products can be sold as a unit. For example, let’s say we want to sell the camera lens + a memory card + a camera. Each of those items would be simple products; we want to sell them as a group so that we can sell them in an offer.

Bundled Product:-
Simple to what group product was doing but group product does give any choice to end user to select. Thus we have bundled product, for example, we can have a memory card with different warranty or of a different company. Now in bundle, we can allow a customer to choose any one of the options with the product.

Virtual Product:-
These are not the physical product, they are sort of services or anything which cannot be touched and feel. Such as cable repairing.

Downloadable product:-
A video, images anything that you can download are included in these product type.

3. What is ORM and how does it work in Magento?

ORM stands for Object Relational Mapping, it is a programming technique for converting data into objects and vice-versa. In Magento, it is implemented as a model, as all Model inherits Varien_Object class and heavily used PHP getter and setter functions to retrieve data objects.
For example:-
$product = Mage::getModel(‘catalog/product’)->setPrice(100);
echo $product->getPrice();

Above we are setting the price as 100 for product but model is not directly interacting with the database it is rather dealing with objects, not with data. Thus if we are using ORM then developer with set and get values through objects they will not be directly interacting with the database.

4. Does Magento follow Master-slave architecture, if yes then tell us how do we create that in Magento?

Yes, Magento support master-slave architecture. It is capable of splitting off reads/writes to different database servers mainly to a master and to a slave which allow us to route read request to additional servers and forwarding all the update/write queries to a single master. Let us see now how we can configure master-slave with Magento:-
In your app/etc/local.xml add a node for default_read and pass the slave database details:-

<default_setup>
    <connection>
        <host><![CDATA[Master-host]]></host>
        <username><![CDATA[user]]></username>
        <password><![CDATA[pass]]></password>
        <dbname><![CDATA[magentodb]]></dbname>
        <active>1</active>
    </connection>
</default_setup>
<default_read>
    <connection>
        <use/>
        <host><![CDATA[Slave-host]]></host>
        <username><![CDATA[user]]></username>
        <password><![CDATA[pass]]></password>
        <dbname><![CDATA[magento]]></dbname>
        <type>pdo_mysql</type>
        <model>mysql4</model>
        <initStatements>SET NAMES utf8</initStatements>
        <active>1</active>
    </connection>
</default_read> 

Secondly, you need to modify MySQL configuration file, make sure we do it before changing local.xml
Configuration for master server
edit /etc/my.cnf and add below content in the file:

[mysqld]
server-id       = 1
log_bin         = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size     = 100M
binlog_do_db        = magento_demo
binlog_ignore_db    = mysql 

then restart your mysql server. Configuration for slave server edit /etc/my.cnf and add below content in the file:

[mysqld]
server-id=2
log-bin=mysql-bin
master-host=192.168.1.2
master-user=username
master-password=111111
master-port=3306
replicate-do-db=magento_demo
replicate-ignore-db=mysql
master-connect-retry=60 

then restart your mysql server.

Above changes will make your architecture ready.

5. What is the directory structure of Magento?

Below are the main files and folders that you should remember:

app (directory) – This folder contains the modules, themes, configuration and translation files. cron.php – a Cron Job should be set for this file.
downloader (directory) – This is the storage of the web downloader files. It is mainly used for installation and upgrade of Magento through your browser;
index.php – the main index file for Magento;
js (directory) – Contains the pre-compiled libraries of the JavaScript code included in Magento;
lib (directory) – The Magento core code is located in this folder. It contains the PHP libraries;
media (directory) – This stores Magento media files – images, thumbnails, uploaded products images.
skin (directory) – This directory contains – images, JavaScript files, CSS files, Flash files.
var (directory) – Cache, sessions, database backups, data exports and cached error reports can be found in this directory;

6. What is the difference between cron.php and cron.sh?

Cron.php is a PHP script and cron.sh is a shell script, cron.sh internally calls cron.php itself. We set Cron file on the server in Cron jobs when we schedule cron. If PHP variable id not set we can directly use cron.sh.

7. How Cron jobs are scheduled in Magento and what is the workflow of Cron in Magento? In which table did we manage Cron schedule?

Cron is a daemon that executes automatically at scheduled time. Sometimes we have requirements in our applications that needs to be automated such as indexing, backup of various things cannot be always taken care manually on daily basis. Thus we write scripts and set Cron them. Magento itself provide a way to configure or schedule a Cron job. Magento uses the cron.php file, which can be found in the root of your application to manage and dispatch cronjobs. The cron.php script internally executes Magento cronjob manager. It is highly recommended to set Cron job using cron.sh rather than cron.php.Cron_Schedule table manages all Cron schedule.

8. What is compilation in Magento? How does compilation improve performance?

Magento Compilation allows you to compile all Magento installation files in order to create a single include path. since all the class files are included and found at the same path it improves the class loading time and thus the performance of your online store is supposed to give between 25% and 50% increase in your page load speed. During development phase we keep compilation off, else we need to run compilation again and again. To disable Magento Compilation, go to your Admin Panel -> System -> Tools -> Compilation and click on the Disable button.
When we run compilation process Magento copies all your class, model, helper, blocks, and lib files to “includes/src” folder. We can check that by opening “includes/src” folder, there you will find the class directly inside a single folder. There will be files with the name as follows : – Mage_Catalog_Block_Breadcrum.php, Varien_Profile.php etc directly in a single folder itself.

In index.php below code is executed, which include file that define compilation path

$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}

Here is the /includes/conig.php file code that is included in above code:-

#define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');

Now in Mage.php you can see that if compilation path is set than class are directly loaded from include/src folder

if (defined('COMPILER_INCLUDE_PATH')) {
    $appPath = COMPILER_INCLUDE_PATH;
    set_include_path($appPath . PS . Mage::registry('original_include_path'));
    include_once COMPILER_INCLUDE_PATH . DS . "Mage_Core_functions.php";
    include_once COMPILER_INCLUDE_PATH . DS . "Varien_Autoload.php";
} else {
    /**
     * Set include path
     */
    $paths = array();
    $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';
 
    $appPath = implode(PS, $paths);
    set_include_path($appPath . PS . Mage::registry('original_include_path'));
    include_once "Mage/Core/functions.php";
    include_once "Varien/Autoload.php";
}

9. What is the difference between resource model, collection, and model?

Model in Magento handles logical operation with the database. There are several kinds of model like
ActiveRecord/one-object-one-table Model, an Entity Attribute Value (EAV) Model. Each Model also gets a Model Collection.
A Magento model object contains a reference to a resource model, which interacts with the database on behalf of the “model”. It is the one who performs CRUD operation on the database.
Collection model contains code that fetched a group of model objects. On collection, we implement filtration and sorting kinds of features. Collection objects inherit from a different chain of classes than the normal resource models, It is also considered a resource model and is instantiated with the Mage::getResourceModel method.

10. What is the difference between a flat table and EAV model?

Though we have covered this in the first question of this page also but let’s discuss more of it. EAV is an entity attribute value database model, where data is fully in normalized form. In Eav model, each data value is stored in their respective data type table. Example, for a product, product ID is stored in catalog_product_entity_int table, product name in catalog_product_entity_varchar, product price in catalog_product_entity_decimal, product created date in catalog_product_entity_datetime and product description in catalog_product_entity_text table. EAV model is complex and thus slow as it joins several tables to retrieve even a simple information.

A flat model uses just one table, so it’s not normalized and thus it uses more database space. It is faster than EAV in retrieving information but it is not good for dynamic requirements where you may have to add more columns in a database table in future. It’s good when comes to performance, as it will only require one query to load whole product. Columns are called fields in flat model. Magento uses indexing process to manage data in flat tables for products so that frontend can be speed up.

Magento Interview Question Part-1

I have been interviewing in Magento from last three years and also given several ;). Below I am sharing my experience and also basic Magento question that interviewer frequently asked.

1. What is Magento?
Well nobody will ask you this silly question, but just to start let’s discuss this. It is an open source e-commerce platform, enriched with lots of functionality and it has a very strong catalog management system which is unbeatable by any other platform in a market.

2. What is code pool in Magento? How many types of they are?
Most basic which every Magento developer know, Magento has provided a different section to for writing up your module and provided different significance to them, basically, three code pools are there: core, local and community.
Below is the Purpose of different code pool:-
Core :- Magento core developer code is placed here. We never place our code in core code pool, neither make any changes over here.
Local :- Magento developer who make their own module or customized Magento default functionality place their code here.
Community :- When we download an extension from Magento community then we normally place extension here.

There is a sequence in which Magento calls these code pool. Suppose the same file is overridden in local and community then local is always given preference. As it can be seen in Mage.php line 43

    $paths = array();
    $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';

Above code clearly tells that firstly local, then community, then core code pool will be executed. Thus when we override our file we place them mostly under local code pool.

3. What are routers in Magento and tell the sequence in which they are called?
Magento uses a front controller which instantiate router object and router object check the request URL for the match with controller and action. Thus routers are responsible for routing a request in Magento. Magento uses four type of router and they are called in below sequence:-
Mage_Core_Controller_Varien_Router_Admin
Mage_Core_Controller_Varien_Router_Standard
Mage_Cms_Controller_Router
Mage_Core_Controller_Varien_Router_Default

Code can be seen in Mage_Core_Controller_Varien_Front class on line 169 in dispatch() function

while (!$request->isDispatched() && $i++ < 100) { foreach ($this->_routers as $router) {
                /** @var $router Mage_Core_Controller_Varien_Router_Abstract */
                if ($router->match($request)) {
                    break;
                }
            }
        }

A loop is executed maximum 100 times for each request if it does not fall under any router and request are matched will all router sequentially.

4. How can we enhance the Magento performance?
This question has vast options to answer with, your practical knowledge can provide a better answer but below are some steps that we do take before moving our web application to a production environment to speed up Magento.
Disable the Magento log (Writing up log might take some time thus disabling then helps in speeding up but you will then not be able to find out the reason of certain issue. In that case forced log option helps)
Disable any unused modules(we should take care not to enable any unused module as it will then be an overhead on Magento because config of that module will always be taken care of)
Magento Caching
Enable Gzip compression
Optimize your image
Optimize your Server
Use a Content Delivery Network (CDN)
USE Gzip Components
Put Stylesheets at the Top (CSS Files in head tag). Also, there is an option to merge all your stylesheet and JS file into single file to reduce HTTP request.
Put Scripts at the Bottom (JS files in footer)
Avoid CSS Expressions (100/2) Minor but can be taken care of.

5. What technology does Magento use?
This could be the silliest question that can be asked from a fresher. Well, Magento uses PHP for programming and MYSQL for database.

6. List different design pattern that Magento use?
This is a very known question for Magento people. Magento follows several types of design pattern such as:-
Singleton Pattern
Factory Pattern
Front Controller Pattern
Registry Pattern
Event Observer Pattern
Prototype Pattern
Object Pool Pattern
Iterator Pattern
Lazy Loading Pattern
Module pattern

7. Describe Singleton and factory pattern. what is the difference between them and how does Magento uses them?
The Singleton pattern is responsible for instantiating a class but it first verifies that if an object of that class is already instantiated or not, if yes then it will return an already created object. On the other side, Factory pattern is also responsible for factorizing (instantiating) classes. It’s widely used throughout the Magento and leverages the autoloading system in Magento. By defining an alias in module config.xml file we are letting the factory know where it can find classes.
For using singeleton pattern we uses Mage::getSingleton(“class alias”); mainly we use it for customer/session, core/session
For using factory pattern we have Mage::getModel(“class alias”);

getSingleton and getModel function definition is found in Mage.php

8. what is the difference between using $this->__(“any text”) and Mage::helper(‘catalog’)->(“any text)?
Well, both works similarly and get the text from a language file. But Mage::helper(‘catalog’)->(“any text”) make sure that specific helper will be used for translation. For example,
Suppose we have a class Mage_Adminhtml_Block_Catalog_Product_Grid_Block
Now, for column header we have,
“header” => Mage::helper(“catalog”->__(“Name”)
So if we will not specify catalog here then adminhtml helper will be considered.

Also, suppose we override some file then also issue can come. For example we have class Mage_Catalog_Block_Breadcrumbs and there is code Mage::helper(“catalog”)->__(“Home”)
Now we override namespace_Modulename_Block_Breadcrumb
if $this->__(“Home”) was used then “Modulename” was used.

9. What is lazy loading?
In Magento Lazy loading is mainly used in ORM or in DATA Mapper, as the name suggest it delays loading of an object until object is called upon. In magento lazy loading is mainly utilized with data not objects.
For example, we heavily uses collection in Magento and we have below code:-

       $collection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('price')
            ->addStoreFilter($this->getRequest()->getParam('store'))
            ->joinField('position',
                'catalog/category_product',
                'position',
                'product_id=entity_id',
                'category_id='.(int) $this->getRequest()->getParam('id', 0),
                'left');
        $this->setCollection($collection);

Above code is just setting or making a query for the database but it is not actually interacting with DB until we actually want to get the data. So if we use $collection->getData() then the collection will interact with database, so it has delays the loading of data.

10. What are getter/setter methods and how does Magento uses them?
PHP has certain magic methods which are called automatically according to their implementation. For example,
__call() :- This method is called automatically when PHP cannot find a method which is called somewhere.

In lib/varien/object.php we have defined this method

public function __call($method, $args)
    {
        switch (substr($method, 0, 3)) {
            case 'get' :
                //Varien_Profiler::start('GETTER: '.get_class($this).'::'.$method);
                $key = $this->_underscore(substr($method,3));
                $data = $this->getData($key, isset($args[0]) ? $args[0] : null);
                //Varien_Profiler::stop('GETTER: '.get_class($this).'::'.$method);
                return $data;

            case 'set' :
                /* Some code here */
            case 'uns' :
                /* Some code here */

            case 'has' :
                /* Some code here*/
        }
        throw new Varien_Exception("Invalid method ".get_class($this)."::".$method."(".print_r($args,1).")");
    }

So above you can see case that checks for ‘get’, ‘set’, ‘uns’ and ‘has’. These methods are called whenever Magento code calls any method which is not defined anywhere throughout the code. Now we knows that to fetch value of any field we use getdata(‘fieldname’) function and we also have another way getFieldName()
Now GetData() is a function that is found in lib/varien/object.php and will thus return us with required value but getFieldName() is not defined anywhere so __call will be called and as it can be seen above it will then get the method name and execute as per required functionality.

PHP Series Program

Below are some series based practice program that can be practiced for interviews:

Series:- 1 + 2 + 3 + 4 + 5 + … + n

// 1 + 2 + 3 + 4 + 5 + ... + n

$n = 10;
for ($i = 1; $i &lt;= $n; $i++) {
 $sum+=$i;
}
echo "Sum of 1 + 2 + 3 + 4 + 5 + ... + n is " . $sum;

 

Series:- (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + … + (n*n)


// (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)
$n = 10;
for ($i = 1; $i &lt;= $n; $i++) {
 $sum+=$i * $i;
}
echo "Sum of (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n) is " . $sum;

 

Series:- (1) + (1+2) + (1+2+3) + (1+2+3+4) + … + (1+2+3+4+…+n)

// (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n)
$n = 10;
for ($i = 1; $i &lt;= $n; $i++) {
 for ($j = 1; $j &lt;= $i; $j++) {
 $sum+=$j;
 }
}
echo "Sum of (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n) is " . $sum;

 

Series:- 1! + 2! + 3! + 4! + 5! + … + n!

//1! + 2! + 3! + 4! + 5! + ... + n!
function fact($n) {
 $f = 1;
 for ($i = 1; $i &lt;= $n; $i++) {
 $f = $f * $i;
 }

 return $f;
}

$sum = 0;
$n = 5;
for ($i = 1; $i &lt;= $n; $i++) {
 $sum = $sum + fact($i);
}
echo "Sum of 1! + 2! + 3! + 4! + 5! + ... + n! is " . $sum;

 

Series:- (1^1) + (2^2) + (3^3) + (4^4) + (5^5) + … + (n^n)

// (1^1) + (2^2) + (3^3) + (4^4) + (5^5) + ... + (n^n)
function power($a, $b) {
 $p = 1;
 for ($i = 1; $i &lt;= $b; $i++) {
 $p = $p * $a;
 }
 return $p;
}

$sum = 0;
$n = 5;
for ($i = 1; $i &lt;= $n; $i++) {
 $sum = $sum + power($i, $i);
}
echo "Sum of (1^1) + (2^2) + (3^3) + (4^4) + (5^5) + ... + (n^n) is " . $sum;

 

Series:- (1!/1) + (2!/2) + (3!/3) + (4!/4) + (5!/5) + … + (n!/n)

// (1!/1) + (2!/2) + (3!/3) + (4!/4) + (5!/5) + ... + (n!/n)
function factorial($n) {
 $f = 1;
 for ($i = 1; $i &lt;= $n; $i++) {
 $f = $f * $i;
 }
 return $f;
}

$sum = 0;
$n = 5;
for ($i = 1; $i &lt;= $n; $i++) {
 $sum = $sum + (fact($i) / $i);
}
echo "Sum of (1!/1) + (2!/2) + (3!/3) + (4!/4) + (5!/5) + ... + (n!/n) is " . $sum;

 

Series:-  [(1^1)/1] + [(2^2)/2] + [(3^3)/3] + [(4^4)/4] + [(5^5)/5] + … + [(n^n)/n]

// [(1^1)/1] + [(2^2)/2] + [(3^3)/3] + [(4^4)/4] + [(5^5)/5] + ... + [(n^n)/n]

function pow($a, $b) {
 $p = 1;
 for ($i = 1; $i <= $b; $i++) {
 $p = $p * $a;
 }
 return $p;
}

$sum = 0;
$n = 5;
for ($i = 1; $i <= $n; $i++) {
 $sum = $sum + (pow($i, $i) / $i);
}
echo "Sum of [(1^1)/1] + [(2^2)/2] + [(3^3)/3] + [(4^4)/4] + [(5^5)/5] + ... + [(n^n)/n] is " . $sum;

 

Series:- [(1^1)/1!] + [(2^2)/2!] + [(3^3)/3!] + [(4^4)/4!] + [(5^5)/5!] + … + [(n^n)/n!]

// [(1^1)/1!] + [(2^2)/2!] + [(3^3)/3!] + [(4^4)/4!] + [(5^5)/5!] + ... + [(n^n)/n!]
function power($a, $b) {
 $p = 1;
 for ($i = 1; $i <= $b; $i++) {
 $p = $p * $a;
 }
 return $p;
}

function fact($n) {
 $f = 1;
 for ($i = 1; $i <= $n; $i++) {
 $f = $f * $i;
 }
 return $f;
}

$sum = 0;
$n = 5;
for ($i = 1; $i <= $n; $i++) {
 $sum = $sum + power($i, $i) / fact($i);
}
echo "Sum of [(1^1)/1!] + [(2^2)/2!] + [(3^3)/3!] + [(4^4)/4!] + [(5^5)/5!] + ... + [(n^n)/n!] is " . $sum;

 

Series:- 1/2 – 2/3 + 3/4 – 4/5 + 5/6 – …… n


// 1/2 - 2/3 + 3/4 - 4/5 + 5/6 - ...... n
$sum = 0;
$n = 10;
for ($i = 1; $i <= $n; $i++) {
 if ($i % 2 == 1)
 $sum+=$i / ($i + 1);
 else
 $sum-=$i / ($i + 1);
}
echo "Sum of 1/2 - 2/3 + 3/4 - 4/5 + 5/6 - ...... n is " . $sum;

Series:- 1 2 3 6 9 18 27 54…

// 1 2 3 6 9 18 27 54...
$a = 1;
$b = 2;
$n = 10;

for ($i = 3; $i <= $n; $i++) {
 if ($i % 2 == 1) {
 $a = $a * 3;
 echo $a . ' ';
 } else {
 $b = $b * 3;
 echo $b . ' ';
 }
}

Series:- 2 15 41 80 132 197 275 366 470 587

// 2 15 41 80 132 197 275 366 470 587

$a = 2;
$n = 10;
for ($i = 1; $i <= $n; $i++) {
 echo $a . ' ';
 $a+=13 * $i;
}

Php Star Pattern Program

Most of us stuck with star pattern program, here are some of them you can practice and find the code for:-

Program for Full Pyramid Using Star

untitled2

// Outer loop for changing rows 
for ($i = 1; $i <= 5; $i++) {

 //Loop added for spacing 
 for ($j = $i; $j <= 5; $j++) {

 echo "&nbsp;&nbsp;";
 }

 //Loop to print star as needed 
 for ($k = 1; $k < ($i * 2); $k++) {
 echo "*";
 }
 echo "</br>";
}

Program For Another Star Pattern
untitled1


// Outer loop for changing rows of full pyramid
for ($i = 1; $i <= 5; $i++) {
 //Loop added for spacing 
 for ($j = $i; $j < 5; $j++) {
 echo "&nbsp;&nbsp;";
 }

 //Loop to print star as needed 
 for ($k = 1; $k < ($i * 2); $k++) {
 echo "*";
 }
 echo "</br>";
}

// Outer loop for changing rows of inverted pyramid
for ($i = 4; $i >= 1; $i--) {
 //Loop added for spacing 
 for ($j = 5; $j > $i; $j--) {
 echo "&nbsp;&nbsp;";
 }

 //Loop to print star as needed 
 for ($k = 1; $k < ($i * 2); $k++) {
 echo "*";
 }
 echo "</br>";
}

Program For Star Pattern With Space In A Rhombus

untitled3


// Outer loop for changing rows
for ($i = 1; $i <= 5; $i++) {

 //Loop added for outer spacing 
 for ($j = 5; $j > $i; $j--) {
 echo "&nbsp;&nbsp;";
 }
 echo "*";

 //Loop added for internal spacing 
 for ($j = 1; $j < ($i - 1) * 2; $j++) {
 echo "&nbsp;&nbsp;";
 }
 if ($i == 1)
 echo "</br>";
 else
 echo "*</br>";
}

// Outer loop for changing rows
for ($i = 4; $i >= 1; $i--) {

 //Loop added for outer spacing 
 for ($j = 5; $j > $i; $j--) {
 echo "&nbsp;&nbsp;";
 }
 echo "*";

 //Loop added for internal spacing 
 for ($j = 1; $j < ($i - 1) * 2; $j++) {
 echo "&nbsp;&nbsp;";
 }
 if ($i == 1)
 echo "</br>";
 else
 echo "*</br>";
}

Program For Inverted Pyramid Using Star

star_pattern

// Outer loop for changing rows
for ($i = 5; $i >= 1; $i--) {
 //Loop added for spacing 
 for ($j = 5; $j > $i; $j--) {
 echo "&nbsp;&nbsp;";
 }

 //Loop added for printing star
 for ($k = 1; $k < ($i * 2); $k++) {
 echo "*";
 }
 echo "</br>";
}

Another Star Pattern

star_pattern1


// Outer loop for changing rows
for ($i = 1; $i <= 5; $i++) {
 for ($j = 1; $j <= 6 - $i; $j++) {
 echo "*";
 }
 for ($k = 1; $k < $i; $k++) {
 echo "&nbsp;&nbsp;&nbsp;&nbsp;";
 }
 for ($j = 1; $j <= 6 - $i; $j++) {
 echo "*";
 }
 echo "</br>";
}

// Outer loop for changing rows
for ($i = 2; $i <= 5; $i++) {
 for ($j = 1; $j <= $i; $j++) {
 echo "*";
 }
 for ($k = 1; $k <= 5 - $i; $k++) {
 echo "&nbsp;&nbsp;&nbsp;&nbsp;";
 }
 for ($j = 1; $j <= $i; $j++) {
 echo "*";
 }
 echo "</br>";
}

Program For Right Angle Triangle Using Star

right1


for ($i = 1; $i <= 5; $i++) {
 for ($j = 1; $j <= $i; $j++) {
 echo "*";
 }
 echo "</br>";
}

Program For Right Angle Inverted Triangle Using Star

inverted_right1

for ($i = 5; $i >= 1; $i--) {
 for ($j = 1; $j <= $i; $j++) {
 echo "*";
 }
 echo "</br>";
}

Program For Right Angle Triangle Using Star

inverted

for ($i = 5; $i >= 1; $i--) {
 for ($j = 1; $j < $i; $j++) { echo "&nbsp;&nbsp;"; } for ($k = 5; $k >= $i; $k--) {
 echo "*";
 }
 echo "</br>";
}

Program For Right Angle Inverted Triangle Using Star

right1

for ($i = 5; $i >= 1; $i--) {
 for ($j = 5; $j > $i; $j--) {
 echo "&nbsp;&nbsp;";
 }
 for ($k = 1; $k <= $i; $k++) {
 echo "*";
 }
 echo "</br>";
}