Wednesday, March 18, 2015

Advanced Object-Oriented Programming in PHP

Object-oriented programming (OOP) is an important technique regardless of the programming language developers use, and PHP is no exception. This article will discuss how to develop advanced object-oriented programs in PHP.

Introduction

PHP is a server side scripting language used to develop web pages. In the recent times, PHP has become popular because of its simplicity. PHP code can be combined with HTML code and once the PHP code is executed, the web server sends the resulting content in the form of HTML or images that can be interpreted by the browser. We all know the power and importance of object-oriented programming or OOP. This is a technique that is widely used in the modern programming languages.

Common OOP Concepts Used in PHP

Inheritance – Inheritance is the most important concept of Object-oriented programming used in most common programming language. Inheritance is based on the principle of parent and child classes. In PHP we achieve inheritance by extending the class. By extending a class, the child class inherits the properties of the parent class and additionally we can add a few more properties.

Listing 1 – Sample code to show inheritance
class Employee {
 public $firstName = "";
 public $lastName = "";
 public $eCode = "";
 public $dept = "";
 
 public function dailyCommonTask() {
  // Code for routine job
 }
}

class Accountant extends Employee {
 public function processMonthlySalary($eCode) {
  // Code for processing salary
 }
}

In the code snippet above we see that the class Accountant is extending the Employee class. An accountant is an employee first, so he performs the daily common jobs as other employees do. At the same time, it is the Accountant's job to process the salary of other employees.

Public, Private and Protected – As in any object-oriented language, PHP also includes the concept of Public, Private and Protected access modifiers.

      • Public – With having public access the code is visible and can be modified by any code from anywhere.
      • Private – With having private access the code is visible and can be modified from within the class only.
      • Protected – With having protected access the code is visible and can be modified from the same class or any of its child class.

Overloading – The overloading feature enables us to have two methods with same name but with different parameters. Shown in the following code snippet:

Listing 2 – Sample code to show overloading
class Accountant extends Employee {
 public function processMonthlySalary($eCode) {
  // Code for processing salary
 }
 public function processMonthlySalary($eCode, $variablePayFlag, $variablePercentage) {
  if($variablePayFlag) {
     echo "Please process the salary with variable pay ";
  } else {
     echo " Please process the salary without variable pay ";
  }
 }
}

In the code above, we have two methods with the same name ('processMonthlySalary'). In an organization, not all the employees will have the variable pay component in their salary. Hence the accountant will have to process the salary using two different approaches:

      • With variable pay
      • Without variable pay

While processing the salary with variable pay, the accountant needs to mention the amount of the variable pay component.

Note of clarification added after original article post date:
In the above example, we explained the general concept of method overloading. But during actual implementation, we need a PHP function called func_get_args () to handle multiple method signature (having same method name) with different arguments. The func_get_args ()is used inside a PHP function which holds all the arguments (as an array) passed into it. So the same function can be called with different arguments.

For example, let us take a function called myTestFunction () and we want to use it as an overloaded function.

function myTestFunction() 
{
    print_r(func_get_args());
}

Now, multiple calls to this function could be as shown below. The func_get_args ()will have all the arguments which can be used as per requirement. The first call does not pass any argument, the second call passes one argument and the third one sends two arguments. So the function is acting as an overloaded function.

myTestFunction ();
myTestFunction ("Hello");
myTestFunction ("Hello","Dear"); 

There is also another way of implementing overloading in PHP — by using __call() and __callStatic() methods.

For example, the code snippet below shows the arguments passed into it along with the method name. Here $name is case sensitive. The output will print the method name and the arguments passed into it.

public function __call($name, $arguments)
    {

        echo "We are calling in object context '$name' "
             . implode(', ', $arguments). "\n";
    }

public static function __callStatic($name, $arguments)
    {

        echo "We are calling in static context '$name' "
             . implode(', ', $arguments). "\n";
    } 

Accessors and Mutators – Commonly known as getters and setters, or Accessors and Mutators, are widely used in every programming language. Accessors (or getters) are functions that are used to return or get the value of the class level variables. Mutators (or setters) are functions that are used to set or modify the value of a class level variable. These types of classes are used to transfer the data in a collective way from one layer to another. Let us consider the following example:

Listing 3 – Sample code for Accessors and Mutators
class Employee {
 public $firstName =  "";
 public $lastName = "";
 public $eCode =  "";
 public $dept = "";
  public function getfirstName() {
  return $this->firstName();
 }
 public function setfirstName($firstName) {
  $this->firstName = $firstName;
 }
 public function getlastName() {
  return $this->lastName();
 }
 public function setlastName($lastName) {
  $this->lastName = $lastName;
 }
 public function getECode() {
  return $this->eCode();
 }
 public function setECode($eCode) {
  $this->eCode = $eCode;
 }
 public function getDept() {
  return $this->dept();
 }
 public function setDept($dept) {
  $this->dept = $dept;
 }
}

These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another.

Static – Using a static keyword for both variable and method is a common practice in object-oriented programming. Static means that the variable or the method is available per instance of the class. Static methods or variables are used without creating an instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods you must take care that the $this variable is not allowed within a static method.

Listing 4 – Sample code for static keyword and method
class StaticSample {
    public static $my_static = 'Sample Static variable';
    public function staticValue() {
        return self::$my_static;
    }
 public static function aStaticMethod() {
        echo "This is the Hello message from static method";
    }
}

class StaticShow extends StaticSample {
    public function checkStatic() {
        return parent::$my_static;
    }

 public function checkStaticMethod() {
        return parent::$aStaticMethod;
    }
}

Abstract Class – In PHP, these two features of object-oriented programming are used very frequently. Abstract classes that can't be instantiated rather they can be inherited. The class that inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword – 'abstract'.

Listing 5 – Sample code for Abstract Class
abstract class testParentAbstract {
 public function myWrittenFunction() {
  // body of your funciton
 }
}

class testChildAbstract extends testParentAbstract {
 public function myWrittenFunctioninChild() {
  // body of your function
 }
}

In the above example, we can create an instance of the child class – testChildAbstract, but we can't create the instance of the parent class – testParentAbstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need.

Interface – In object-oriented programming, the interface is a collection of definitions of some set of methods in a class. By implementing an interface, we force the class to follow the methods defined in the interface. In PHP, interface is defined like in any other language. First we need to define the interface using the keyword – 'interface'. When implementing, we just need to mention the 'implements' keyword in the implementing class.

Listing 6 – Sample Code for Interface
interface myIface {
 public function myFunction($name);
}

class myImpl implements myIface {
 public function myFunction($name) {
  // function body
 }
}

Summary


PHP has emerged as one of the most popular languages for web application development. It has been enhanced to support different aspects of programming and of those, the object-oriented features are the most important to understand and implement.

Monday, March 16, 2015

Difference between Zend_Registry and Zend_Session?

The basic difference between these objects is the ‘scope’ in which they are valid:

a) Zend_Registry : request scope
b) Zend_Session : session scope

a) Zend_Registry is used to store objects/values for the current request. In short, anything that you commit to Registry in index.php can be accessed from other controllers/actions (because EVERY request is first routed to the index.php bootstrapper via the .htaccess file). Config parameters and db parameters are generally prepped for global use using the Zend_Registry object.

b) Zend_Session actually uses PHP sessions. Data stored using Zend_Session can be accessed in different/all pages. So, if you want to create a variable named ‘UserRole’ in the /auth/login script and want it to be accessible in /auth/redirect, you would use Zend_Session.

What are Plugins in zend framework?

• Triggered by front controller events
• Events bookend each major process of the front controller
• Allow automating actions that apply globally
Creating Plugins:
• Extend Zend_Controller_Plugin_Abstract
• Extend one or more of the event methods

what is routing and how it's work?

Zend_Controller_Router_Rewrite is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request. This values of the module, controller, action and other parameters are packaged into a Zend_Controller_Request_Http object which is then processed by Zend_Controller_Dispatcher_Standard. Routing occurs only once: when the request is initially received and before the first controller is dispatched.

Zend_Controller_Router_Rewrite is designed to allow for mod_rewrite-like functionality using pure PHP structures. It is very loosely based on Ruby on Rails routing and does not require any prior knowledge of webserver URL rewriting. It is designed to work with a single Apache mod_rewrite rule.

What is zend engine?


 Zend Engine is used internally by PHP as a complier and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes.

Zend engine is like a virtual machine and is an open source, and is known for its role in automating the web using PHP. Zend is named after its developers Zeev and Aandi. Its reliability, performance and extensibility has a significant role in increasing the PHP’s popularity. The Zend Engine II is the heart of PHP 5. It is an open source project and freely available under BSD style license.

Creating Your Own Helper – Zend Framework

In Zend Framework, most of the important functions are built into the framework. Most of them are in the View Helpers or Action Helper. But in big projects, you will always need to inject some functionality that are too small to create a class/plugin.
You can always create a protected function inside a controller, but what if that function is needed in more than one controller? Creating a base controller that you will extend later will only create troubles when controllers don’t initialize properly or if not all controllers need those functionalities.
So, here is how to create your own helper (of course this can be found on the zend framework online manual):

1. Create the helper directory structure

Your helper class name must be compatible with Zend’s naming conventions to allow Zend_Loader to load it automatically. Your helper must be placed on a directory that is set in include path. In my case I have only one included path and that is the library directory, so I placed them there:
  • library/Zend/[Zend Library]
  • library/Dc/Helper/[My Helpers] - this is where my helpers located

2. Tell Zend Framework the location of your helpers

So that Zend Framework includes your helpers, add this line to your bootstrap:

/**
 * Setup the Custom Helpers
 */
Zend_Controller_Action_HelperBroker::addPrefix('Dc_Helper');
That way, the folder Dc/Helper/ is read along with other default helper paths when loading a helper.

3. Create the helper

Now, it’s time to create the actual helper. To create the helper, you must extend Zend_Controller_Action_Helper_Abstract and do some initialization on the constructor.
The helper below is called DaysInMonth, which returns the number of days in a certain month where month and year is given.

/**
 * Action Helper for finding days in a month
 */
class Dc_Helper_DaysInMonth extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * First entry is for January
     */
    protected $daysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
     
    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;
 
    /**
     * Constructor: initialize plugin loader
     *
     * @return void
     */
    public function __construct()
    {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
    }
 
    /**
     * Returns the number of days in a given month + year
     *
     * @param int $month
     * @param int $year
     * @return int
     * @throws Exception
     */
    public function getDaysInMonth($month, $year)
    {
        if ($month < 1 || $month > 12)
        {
            throw new Exception('Invalid month ' . $month);
        }
    
        $d = $this->daysInMonth[$month - 1];
    
        if ($month == 2)
        {
            // Check for leap year
            // Forget the 4000 rule, I doubt I'll be around then...
         
            if (($year % 4) == 0)
            {
                if (($year % 100) == 0)
                {
                    if (($year % 400) == 0)
                    {
                        $d = 29;
                    }
                }
                else
                {
                    $d = 29;
                }
            }
        }
     
        return $d;
    }
     
    /**
     * Strategy pattern: call helper as broker method
     *
     * @param  int $month
     * @param  int $year
     * @return int
     */
    public function direct($month, $year)
    {
        return $this->getDaysInMonth($month, $year);
    }
}
The public function direct is the entry point of your helper. It just accepts the parameters then call the function to get the days in a month. That is called Strategy Pattern.
You’ll notice that what I was really trying to create was just the function getDaysInMonth.

4. Call the helper inside your controller

To call my newly created helper, here it is (inside the controller)

$days = $this->_helper->daysInMonth(4, 2009);