PHP code optimization tips and tricks

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

Code optimization is the process of modifying a code to make some aspect of it work efficiently or use fewer resources.

Their are several level of optimizations can be done in software

  • Design Level
  • Source Code Level
  • Infrastructure Level
  • Compile Level

In this article we will focus on some of the tricks for Source Code optimization for a PHP code base.

What is code optimization

Code optimization is the process of transforming a piece of code to make it more efficient without changing its output. A program may be optimized so that it become smaller in size, consume less memory, execute more rapidly, or perform fewer I/O operations.

Continue reading

PHP Autoloading – Part 2 : Recommended

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

In Part 1 we understood that __autoload() works well when all our classes are at one place and follows same naming conventions. However in real world application, classes are divided in different modules and packages, placed at multiple locations. This situation can be handled using __autoload by checking multiple locations inside the __autoload as shown in the following example

function __autoload($className) {
    $path1 = '/var/www/prj/user/';
    $path2 = '/var/www/prj/email/';
    if(file_exists($path1.$className.'.php')) {
        require_once($path1.$className.'.php');
    } else if(file_exists($path2.$className.'.php')) {
        require_once($path2.$className.'.php');
    }
}

but still __autoload can only be used once in the entire application and with the increasing use of third party libraries and large code base __autoload will become bulkier and hard to maintain.

spl_autoload_registor() solves the problem of using large number of third-party library classes. it gives us option to create multiple functions like __autoload to be called one by one until class is loaded or all registered functions get called. Following example explain the basic use of spl_autoload_registor()

File : /var/www/html/autoloading/recommended/User.php

class User {
	public function __construct() {
		echo 'User class found'.PHP_EOL;
	}
}

File : /var/www/html/autoloading/recommended/load.php

function loadClasses($argument) {

	require_once $argument.'.php';

	echo 'autoload get called'.PHP_EOL;
}

spl_autoload_register('loadClasses');

File : /var/www/html/autoloading/recommended/recommended-example.php

require_once 'load.php';

$user = new User();

Output:
autoload get called
User class found

in the above example loadClasses is registered to load our classes instead of __autoload().

Note: __autoload will not get called if spl_autoload_register is used.

Continue reading

PHP Autoloading – Part 1 : Basics

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

Autoload is the programming concept to load and link the portion of a program from mass storage automatically when needed. With increase of classes in PHP projects, PHP introduce auto-loading for loading classes automatically.

Lets understand the basics of autoloading step by step.

Create a class

File : /var/www/html/autoloading/basic/User.php

class User {
	public function __construct() {
		echo 'User class found'.PHP_EOL;
	}
}

Lets try to use the class

File : /var/www/html/autoloading/basic/basic-example.php

require_once 'User.php';

$user = new User();

Output:
User class found.

But wait, this is the old way of including class definitions, what if we have 100 classes in the project, do we need to put 100 includes, yes we need to but then why auto loading feature is introduced. Lets try to use the auto loading.

File : /var/www/html/autoloading/basic/basic-example.php [ updated to use autoloading ]

// require_once 'User.php';

$user = new User();

Output:
PHP Fatal error: Class ‘User’ not found in /var/www/html/autoloading/basic/basic-example.php on line 4

Confused why this output, PHP has autoloading feature, class should be found. Yes output is correct automatically does not mean PHP found all your classes by some magic and you do not have to do anything. In auto-loading PHP gives a last chance to load a class definition if not found by calling a function ‘__autoload()’. It is the developers responsibility to implement __autoload().

Continue reading

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

It is very easy to get lost in a world of assumptions. When we make program, we make assumptions that each piece is going to work as expected. You have to be open minded enough to acknowledge that any single one of your assumptions could be wrong.

Quick Start EC2 with LAMP

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

Following video tutorial show how to quickly setup an AWS EC2 with LAMP.

Following are some links and command used in the video

http://aws.amazon.com

ssh -i public-key.pub ubuntu@ip
apt-get update
apt-get install apache2
apt-get install mysql-server
apt-get install php5 php5-mysql

Note: For using the tutorial you will need an AWS account which you can register by simply providing your details and a credit card. Account setup fee is $1 (can change).

Top 10 symptoms for a developer to make a switch

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

Following are my top 10 reasons for a developer to switch job or look for a alternate carrier.

  1. You have not learned a new thing in last 3 months.
  2. You work hours per week exceeding by 25% regularly.
  3. You are not enjoying the work assigned to you.
  4. You feels work is becoming a peace of cake for you.
  5. You do more meetings then code.
  6. You are doing a new thing every other day.
  7. Your salary is less then the average salary for your domain for your experience.
  8. You got a bed management.
  9. You got a better offer (not just in terms of salary)
  10.  You sometime thinks coding is not your cup off tea, lookout for alternative carrier

Debugging PHP beyond print_r and var_dump

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

echo, print_r and var_dump are the most used functions when it comes to debugging a PHP application. However with the increasing trend of building applications using various frameworks (ZF, Symfony, Cake, Yii etc..) these functions are not very efficient for getting the information about a variable all the time.

More Debugging functions

Following are some lesser known in-build PHP functions and tips are useful for getting a lot of information about variables whiles debugging.

How to get the class name of an object

get_class($object) Returns the name of the class of an object

class Car {
    public function myName() {
        echo get_class($this).PHP_EOL;
    }
}

$obj = new Car();
echo get_class($obj).PHP_EOL;
$obj->myName();

// output
Car
Car

Tip: After knowing the class name you can use grep to find the class file  “grep -lhr ‘new [ClassName] [ProjectRootDir] ( e.g. grep -lhr ‘new Car’ /var/www/. )

Continue reading

PHP date and time tricks

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on StumbleUponShare on RedditDigg thisShare on Tumblr

Manipulating date and time using various date/time functions is integral part of day to day programming for PHP programmers.

Most commonly used date functions are

date(format, [timestamp]) : return the formatted date string. if timestamp is not passed current timestamp is used.

 echo date('m/d/Y'); 

time() : return current time in seconds.

 echo time(); 

strtotime(time, [now]) : return timestamp (no of seconds) for a date string for relative timestamp.

 echo strtotime('2012-03-01'); 

Some Tricks to use php date and time functions

1. To get current date information you just have to pass various formats to date function. Following are some examples of date funtions to get current date information. There can me more ways date function used with different formats for detailed study about formats visit php date manual.

Continue reading