15 Tips to Optimize Your PHP Script for Better Performance for Developers

If you are a developer, it is essential for you to optimize your script early in the development process itself. Following the best practices while coding your PHP script is a good starting point to write a well optimized PHP code.

This tutorial provides few tips to optimize PHP code from a developer point of view.

1. Use Native PHP Functions

As much as possible, try to use native PHP functions rather than writing your own functions to achieve the objective. For example, you can use range( b, k) to get an array of alphabets starting from b to k in sequence, if it is only needed once in the script rather than declaring an array with these values in a function and returning it on its call.

2. Use Single Quotes

Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” ) if you are going to keep only the string inside it avoiding any variables. Double quotes checks for the presence of variable and adds little bit of overhead.

3. Use = = =

Use “= = =” instead of “= =”, as the former strictly checks for a closed range which makes it faster.

4. Use Appropriate Str Functions

str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

5. Calculate Only Once

Calculate and assign the value to the variable if that value is getting used numerous time rather than calculating it again and again where it is being used.

For example, the following will degrade the performance.

for( $i=0; i< count($arrA); $i++){
  echo count($arrA);
}

The script below will perform much better.

$len = count($arrA);
for( $i=0; i< $len; $i++){
  echo $len;
}

6. Pass Reference to Function

Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.

For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.

<?php
  // passing by reference
  function  computeValue( &$param ){
  	// Something goes here
  	foreach( $param as $k => $value){
  	  $param[$k] = $value + 1;
  	}
  }
  $x = array();
  for( $i =0; $i<99; $i++){
    $x[$i] = $i;
  }
  computeValue( $x);
  
  // array with 100 elements each incremented by 1
  print_r( $x );

?>                   		 

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

  <?php
  	// passing by value
    function  computeValue( $param ){
      // Something goes here
      foreach( $param as $k => $value){
      	$param[$k] = $value + 1;
      }
      
      return $param;
    }
    $x = array();
    for( $i =0; $i<99; $i++){
      $x[$i] = $i;
    }
	// array with 100 elements each incremented by 1
    print_r(computeValue( $x));
    
  ?>

7. Create Classes Only When its Required

Don’t create classes and method until and unless its really needed, used and reused as well.

8. Disable Debugging Messages

File operations are expensive. So, if you have written lot of custom functions to log errors and warning during your development process, make sure you remove them before you push the code to production.

9. Use Caching Techniques

Use cache to reduce the load of database operations as well as the script compilation. We can use memcache for the reducing database load and APC for opcode caching and intermediate code optimization.

10. Close the Connection

Get into the habit to unset the variables and close database connection in your PHP code. It saves memory.

11. Reduce Number of Hits to DB

Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times. For example:

<?php
  $con=mysqli_connect("localhost","username","somepassword","anydb");
  
  if (mysqli_connect_errno())
  {
    echo "Failed to connect to MySQL" ;
	mysqli_connect_error(); 
  }

  function insertValue( $val ){
    mysqli_query($con,"INSERT INTO tableX (someInteger) VALUES ( $val )");
  }
  
  for( $i =0; $i<99; $i++){
    //  Calling function to execute query one by one 
    insertValue( $i );
  }					
  // Closing the connection as best practice		
  mysqli_close($con);

?> 

The script above is much slower than the script below:

<?php
  $con=mysqli_connect("localhost","username","somepassword","anydb");
  if (mysqli_connect_errno())
  {
  	echo "Failed to connect to MySQL" ;
  	mysqli_connect_error(); 
  }
   
  function insertValues( $val ){
     // Creating query for inserting complete array in single execution.
    $query= " INSERT INTO tableX(someInteger) VALUES .implode(',', $val)";      
    mysqli_query($con, $query);
  }
  
  $data = array();
  for( $i =0; $i<99; $i++){
    // Creating an array of data to be inserted.
    $data[ ]  =   '(" ' . $i. '")' ;
  }
  // Inserting the data in a single call
  insertValues( $data );
  // Closing the connection as a best practice
  mysqli_close($con);

?> 

12. Frequently Used Switch Cases

Keep most frequently used switch cases on the top.

13. Use Methods in Derived Classes

Methods in derived classes are faster than base classes. For example, let there be a function in both base class and derived class for performing task1. It is named as “forTask1” in base class and “forTask1again” in derived class, so that they will not override.

Call to the function “forTask1again( )” which is in derived class will work faster than call to the function “forTask1( )” as it is from base class.

<?php
  class someBaseClass
  {
  	public function forTask1($string)
  	{
  		// perform task 1
  	}
  	public function forTask2( )
  	{
  		// perform task 2
  	}
  }
  
  class derivedClass extends someBaseClass
  {
  	public function forTask1again($string)
  	{
  		//perform task 1 same as the function in base class.
  	}
  	public function forTask3($string)
  	{
  		//perform task 3
  	}
  }
  //Instantiating the derived class below.
  $objDerivedClass = new derivedClass( ); 
  
  // The call below works slow for task1 as it is from base class.
  $resultTask1 = $objDerivedClass->forTask1( );
  
  // The call below works faster for task1 as 
  // it is from derived class.
  $sameResultTask1 = $objDerivedClass->forTask1again();
?>

14. Use JSON

Use JSON instead of XML while working with web services as there are native php function like json_encode( ) and json_decode( ) which are very fast. If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

15. Use isset

Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.

For example, let us assume that you have a function which returns an array with values or a NULL array. Now you want to check whether the returned array is with values or not, then use the following:

if(isset($returnValue)){
  // do something here
}

In this case, use the above code block, instead of the following:

if(count($returnValue) > 0){
  // do something here
}
Advertisements

Install Cakephp 3 on Ubuntu

Stable version of cake3 is released for use. Old way of downloading cake and placing it in root directory and making changes to it, to get the app working won’t work anymore. We have to install cakephp using composer. I tried installing it on my machine and felt like sharing the steps that I followed to install. So, here it goes

Following are the requirements for installing cakephp3 :
1. HTTP Server like Apache
2. PHP version greater than or equal to 5.4.16
3. mbstring extension
4. intl extension
5. Composer, without which you cannot install cakephp3

Installing Requirements 

Go to Terminal,

Install apache and php >= 5.4.16.

Install mbstring extension using the following command :
sudo apt-get install libapache2-mod-php5

Install intl extension using the following command :
sudo apt-get install php5-intl

Now restart apache using the command :
service apache2 restart

Install Composer :
Once all Apache,PHP, mbstring and intl extension are installed. Next step is to install composer.
Go to your root directory( /var/www/ in ubuntu ) cd /var/www
If you have curl installed you can use command curl shttps://getcomposer.org/installer | php
else you can use command php -r “readfile(‘https://getcomposer.org/installer&#8217;);” | php
to install composer.
Note, commands above will install composer only in the directory where you ran the command.

Now we are ready to install cakephp3
Go to document root directory( /var/www/ in ubuntu ) cd /var/www
Now type the command below :
php composer.phar create-project –prefer-dist cakephp/app [app_name]
Your cakephp3 application will now be running.

Connecting to database :
In cakephp3 we give database connection parameters in app.php in folder <app-name>/config
Go to  <app-name>/config/app.php and change the requires parameters mentioned below
‘Datasources’ => [
         ‘default’ => [

             ‘username’ => ‘<give your db username here>’,
              ‘password’ => ‘<give your db passwoprd here>’,
              ‘database’ => ‘<give your db name here>’,

Type http://localhost/app_name in browser to see your cakephp3 app.

Issues that you might face when you type command
php composer.phar create-project –prefer-dist cakephp/app [app_name]

1. Could not open input file: composer.phar
This means you haven’t installed composer globally, and your composer installation was directory specific. Go to the directory where you have installed the composer and issue the above command.

2. This package requires php >=5.4.16 but your PHP version does not satisfy that requirement.
You will get this error when you are trying to install cakephp3 on php version lesser than 5.4.16.
PHP version of your machine has to be upgraded to version 5.4.16 or greater.
    Note : Restart apache after  the upgrade.

3. cakephp/cakephp 3.0.x-<dev/beta/alpha/RC> requires ext-intl * -> the requested PHP extension intl is missing from your system. 
   This means intl extension for php was not installed. You need to install intl extension as mentioned     above, using the command sudo apt-get install php5-intl .
Note : Restart apache after installing.

Issues that you might face after installing 

1. Database driver Cake\Database\Driver\Mysql cannot be used due to a missing PHP 
    extension or unmet dependency
    The above error will be displayed on browser, if Mysql database driver couldn’t be used by app or
is missing. Type the following command in terminal :
     sudo apt-get install php5-mysql
     Now restart mysql using command service mysql restart then restart Apache using command
service apache2 restart
     Refresh the browser now, the above error would have disappeared.

Overloading and Overriding in PHP

Function or method Overloading and overriding method is very basic and useful feature of any oop language. In this tutorial we will discuss implementation of method overloading and overriding in php.  Here first we will explore basics of overloading and overriding. After exploration of basics we will implement overloading and overriding in php. Before going further I am assuming that you have basic knowledge of classes and inheritance in php. Also you have understanding about magic method in php. Magic method because overloading in php can be implmented using magic methods.

What is Method Overriding in OOP ?

Basic meaning of overriding in oop is same as real word meaning. In real word meaning of overriding  phenomena of replacing the same parental behavior in child. This is same in case of method overriding in oop. In oop meaning of overriding is to replace parent class method in child class. Or in simple technical word method overriding mean changing behavior of the method. In oop overriding is process by which you can re-declare your parent class method in child class. So basic meaning of overriding in oop is to change behavior of your parent class method.

Normally method overriding required when your parent class have some method, but in your child class you want the same method with different behavior. By overriding of method you can complete change its behavior from parent class. To implment method overiding in oop we commonly create same method in child class.

What is Method Overloading in OOP ?

Overloading in oop is same as overloading in real word. In real word overloading means assigning extra work to same machine or person. In oop method overloading is same. By process of method overloading you are asking your method to some extra work. Or in some cases we can say some different work also.

Normally method overloading in oop is managed on the basis of the argument passed in function. We can achieve overloading in oop by providing different argument in same function.

Overloading and Overriding in PHP

Hope your basic concept of overloading and overriding is clear now. Now let us explore implementation of overloading and overriding in php.

Implementation of overriding in php is very easy. If your parent class has a function. You can create function with same name in your child class to override the function. Implementation of overriding can not be achieved by creating 2 function with same name and different argument in php. Because we can not create same name function more than 1 time in php class. To implement overloading we need to take help of magic method in php. In below section we will explore overloading and overriding one by one.

Overloading in PHP

As we know that we can not implement overloading by create 2 function in with same name in class. So to implement overloading in php we will take help of magic method __call. Magic method __call invoked when method called by class object is not available in class. So here we will not create method exactly and will take help of __call method. Now call method will provide us 2 argument, 1st name of the method called and parameter of the function. Now with the help of either switch case or if else we will implement overloading in php. Following is very simple example of overloading in php.

class test
{
public function __construct()
{
//Your logic for constructor
}
public function __call($method_name , $parameter)
{
if($method_name == "overlodedFunction") //Function overloading logic for function name overlodedFunction
{
$count = count($parameter);
switch($count)
{
case "1":
//Business log in case of overlodedFunction function has 1 argument
echo "You are passing 1 argument";
break;
case "2": //Incase of 2 parameter
echo "You are passing 2 parameter";
break;
default:
throw new exception("Bad argument");
}
}
else
{
throw new exception("Function $method_name does not exists ");
}
}
}
$a = new test();
$a->overlodedFunction("ankur");
$a->overlodedFunction("techflirt" , "ankur");

As in above class test magic method __call is implemented which is managing overloading

public function __call($method_name , $parameter)
{
if($method_name == "overlodedFunction") //Function overloading logic for function name overlodedFunction
{
$count = count($parameter);
switch($count)
{
case "1":
//Business log in case of overlodedFunction function has 1 argument
echo "You are passing 1 argument";
break;
case "2": //Incase of 2 parameter
echo "You are passing 2 parameter";
break;
default:
throw new exception("Bad argument");
}
}
else
{
throw new exception("Function $method_name does not exists ");
}
}

As we know that __call magic method invoked when method is not available in the class. So in case of above test class example we have not created function overlodedFunction. So whenever method overlodedFunction is called __call invoked. __call pass 2 variable, first  name of the called method and other is parameter passed in the called function.

Now in the __call function I have applied if condition to ensure that our business logic of overloading works only for overlodedFunction function. In if block we have counted number of argument in parameter and applied business logic.

Overriding in PHP

Overriding in php is very easy. As we know that overriding is process of modifying the inherited method. So in case of inheritance you only need to create method with same name in your child class which you want to override. Following is example of overriding of method in php.

class testParent
{
public function f1()
{
echo 1;
}
public function f2()
{
echo 2;
}
}
class testChild
{
function f2($a) //overriding function f2
{
echo "$a";
}
}
$a = new testChild();
$a->f2("ankur");//it will print ankur

In above example you are overriding function f2. While overriding you are free to change business logic, visibility and number of parameter.

Magic Methods in PHP

Magic methods in php are some predefined function by php compiler which executes on some event. Magic methods starts with prefix __, for example __call, __get, __set. I am including magic methods topic in my oop tutorial here because these method mostly applied in classes of PHP. If you have gone through my previous chapter then you have seen __construct function. __construct is a magic method which automatically call on creating object of the classes. There are verous magic methods in php. Here we will discuss some of the most comman magic methods of php which will be use in object oriented programming. First of let us review all magic method with short description.

 

List of List of Magic Methods in PHP

Magic Method Description
__construct This magic methods is called when someone create object of your class. Usually this is used for creating constructor in php5.
__destruct This magic method is called when object of your class is unset. This is just opposite of __construct.
__get This method called when your object attempt to read property or variable of the class which is inaccessible or unavailable.
__set This method called when object of your class attempts to set value of the property which is really inaccessible or unavailable in your class.
__isset This magic methods trigger when isset() function is applied on any property of the class which isinaccessible or unavailable.
__unset __unset is something opposite of isset method. This method triggers when unset() function called on inaccessible or unavailable property of the class.
__call __call magic method trigger when you are attempting to call method or function of the class which is either inaccessible or unavailable.
__callstatic __callstatic execture when inaccessible or unavailable method is in static context.
__sleep __sleep methods trigger when you are going to serialize your class object.
__wakeup __wakeup executes when you are un serializing any class object.
__toString __toString executes when you are using echo on your object.
__invoke __invoke called when you are using object of your class as function

Above list is the most conman used magic methods in php object oriented programming. Above magic methods of php executes on some specif  events occur on your class object. For example if you simply echo your object then __toString method trigger. Let us create group of related magic method and analyze how it is working.

__construct and __destruct magic method in PHP

__construct method trigger on creation of object. And __destruct triggers of deletion of object. Following is very basic example of __construct and __destruct magic method in php:
class test
{
function __construct()
{
echo 1;
}
function __destruct()
{
echo 2;
}
}
$objT = new test(); //__construct get automatically executed and print 1 on screen
unset($objT);//__destruct triggers and print 2.

__get __set __call and __callStatic Magic Methods

__get, __set, __call and __callStatic all magic methods in php directly related with no accessible method and property of the class.
__get takes one argument and executes when any inaccessible property of the method is called. It takes name of the property as argument.
__set takes two property and executes when object try to set value in inaccessible property. It take first parameter as name of the property and second as the value which object is try to set.
__call method fires when object of your class is trying to call method of property which is either non accessible or not available. It takes 2 parameter  First parameter is string and is name of function. Second parameter is an array which is arguments passed in the function.
__callStatic is a static magic method. It executes when any method of your class is called by static techniques.

Following is example of __get , __set , __call and __callStatic magic methods
class test
{
function __get($name)
{
echo "__get executed with name $name ";
}
function __set($name , $value)
{
echo "__set executed with name $name , value $value";
}
function __call($name , $parameter)
{
$a = print_r($parameter , true); //taking recursive array in string
echo "__call executed with name $name , parameter $a";
}
static function __callStatic($name , $parameter)
{
$a = print_r($parameter , true); //taking recursive array in string
echo "__callStatic executed with name $name , parameter $a";
}
}
$a = new test();
$a->abc = 3;//__set will executed
$app = $a->pqr;//__get will triggerd
$a->getMyName('ankur' , 'techflirt', 'etc');//__call willl be executed
test::xyz('1' , 'qpc' , 'test');//__callstatic will be executed

__isset and __unset magic methods

__isset and __unset magic methods in php are opposite of each other.
__isset magic methods executes when function isset() is applied on property which is not available or not defined. It takes name of the parameter as an argument.
__unset magic method triggers when unset() method is applied on the property which is either not defined or not accessible. It takes name of the parameter as an argument.
Following is example of __isset and __unset magic method in php
class test
{
function __isset($name)
{
echo "__isset is called for $name";
}
function __unset($name)
{
echo "__unset is called for $name";
}
}
$a = new test();
isset($a->x);
unset($a->c);