Archive for the Category ◊ PHP ◊

Author:
Saturday, March 30th, 2013

Singleton pattern is described as a grand daddy of all design patterns. The Singleton pattern is a design pattern which restricts instantiation of a class to one single object. In other words we can say Singleton is a fancy name for a GLOBAL Variable.

The best example for singleton pattern is Database class . You really dont want more than one instance of Database connect in the life cycle of your script. The way we do that that is that we dont make it possible to create a new instance of the class using NEW.

Class DB
{
     private __construct()
    {
        //PRIVATE
     }
}
$db=new DB();

IF we run this script we get FATAL error saying constructor of the class DB is private.

So the way we can create instance of this class is by creating a private static variable.

Class DB{
    private static $instance;
    private __construct()
   {
      //PRIVATE
    }
}
$db=new DB();

Then we create a public static function that gets us the instance

Class DB{
    private static $instance
    private __construct()
   {
    //PRIVATE
    }
   public static function getinstance()
   {
       return DB::$instance = new DB();
   }
   public function query()
  {
     return “select * from tablename”;
   }
}
$db=DB::getInstance();
echo $db->query();

This will return “select * from tablename”.

But if you see the above code , every time you call query function it will always create new instance of that class .

So we our new code is

Class DB{
    private static $instance
    private __construct()
   {
    //PRIVATE
   }
   public static function getinstance()
  {
       if(!isset(DB::$instance))
      {
        DB::$instance = new DB();
      }
return DB::$instance;

  }
public function query()
{
   return “select * from tablename”;
}
}
$db=DB::getInstance();
echo $db->query();

Category: PHP | Tags:  | 2 Comments
Author:
Saturday, March 23rd, 2013

Design patterns are reusable solution to software development issues. It was introduced by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Gang of Four). We can say that they are recurring solutions to common S/w development challenges.

Using design patterns on your application it is very easy to encapsulate your ideas. Design patterns are not specific to any language. However it does depend on capabilities of the language.

You really wont realize the use of design patterns using small examples. It often come into play when there is large code bases .

Since PHP being opensource a lot of PHP developers dont usually follow these principles of Software development. Also these patterns will be in built in Opensource php frameworks , but we hardly know what is happening .

Design patterns are basically classified into 3 kinds

Design-Patterns-Categories

 

 

 

 

 

 

 

 

 

 

 

They are :

  1. Structural
  2. Creational
  3. Behavioral

Structural patterns deals with the relation ship between entities .

Creational patterns creates objects for you, and you can use this objects in a manner that suits your situation.

Behavioral patterns is used in communication between entities and makes it easy for these entities to communicate with each other .

Author:
Sunday, February 10th, 2013

PHP is the most powerful opensource server side scripting language . As a experienced PHP developers we tend to leave back the simple basics and concentrate on high level coding style. Here are the few Basic tips that help you to increase the Performance to some extent.

  1. Use echo wherever possible instead of print . This is because echo is  approx 15-20 %   faster than print.
  2. Do not use the string concatenation. Try to use echo multiple parameter .( echo “Welcome , {$user->firstName} {$user->lastName}”;)
  3. Use include instead of include_once .
    <?php
    var_dump(include_once ‘file.ext’); // bool(false)
    var_dump(include_once ‘file.ext’); // bool(true)
    ?>This is because according to php the file was already included once (even though it does not exist).
  4. Use absolute path’s  in includes and requires.
  5. Use str_replace instead of preg_replace (Depends on the context)
  6. Use elseif statements insted of case/switch
  7. Use  $user['firstname'] instead of  $user[firstname]. The first one is 6-7 times faster than second.
  8. Use isset where possible in replace of strlen. (ie: if (strlen($myname) < 10) { echo “My name is too short”; } vs. if (!isset($myname{10})) { echo “My name is too short”; } ).
  9. Separate your HTML and PHP code . Use MVC .
  10. Don not use   register_globals. Off them in your php.ini (It is off by default).
  11.  If a method can be a static method, declare it static.
  12. Incrementing a Object property is slower than a local variable. approx 3 times.
  13. Use <?php ?> for your php block of code. because short open tags may be disabled in some servers.
  14. Use php memcache for caching .
  15. Use only one type of engine for all the mysql tables. This is because if you use different engines then joining table will slower down the queries.
  16. Do not store any passwords in clean text . Use md5 encryption or any user defined encryption.

Category: PHP  | Leave a Comment
Author:
Monday, February 04th, 2013

Matrix effect using jquery

jQuery is one the amazing frameworks which makes the life of a web developer easy. It is so simple to learn and yet powerful. Below is an example for that.. I tried creating the most famous matrix effect and the code is attached.

Here are the download Links :

(for windows) zipped -> matrix

(for linux) tar.gz compressed -> Matrix.tar

Download the compressed file from above, extract it and just run the index.html from the extracted folder in browser.

Below is the screenshot :

canvas

 

 

Code (from index.html) : 

<html>
<head>
<title>Matrix</title>
<style>
body{background-color:#000000;overflow:hidden;}
#page{overflow:hidden;display:table-cell;vertical-align:middle;}
#logo{color:#00ff00;font-size:0;font-weight:bold;opacity:0.2;}
.thread{top:0px;position:absolute;width:15px;color:#00ff00;font-weight:bold;overflow:hidden;}
</style>
<script src=”jquery.min.js” ></script>
<script src=”jquery.ui.min.js” ></script>
<script>

var winW = window.innerWidth – 10;
var winH = window.innerHeight – 10;
var threadid = 1;
var threadCount = 0;

var titleFontSize = 0;
var removeThreadId = 1;
var maxThreadCount = 100;
var threadAddSpeed = 200;
var animateThreadSpeed = 100;
var threadRemoveSpeed = 1000;

$(document).ready(function(){
$(‘#page’).css(‘width’, winW);
$(‘#page’).css(‘height’, winH);
startAnimation();
});

function startAnimation(){
if(threadCount <= maxThreadCount){
addThread();
if(threadid == maxThreadCount){
removeThread();
zoomInTitle();
}
setTimeout(startAnimation, threadAddSpeed);
}
}
function addThread(){
var curFontSize = Math.floor((Math.random()*10)+6);
var startDigit = Math.floor((Math.random()*10));
var opacity = curFontSize/10;
opacity = (opacity > 1) ? opacity : opacity * 0.3;
var left = Math.floor((Math.random()*winW)+1);
var threadHeight= Math.floor((Math.random()*winH)+50);
$(‘#page’).append(“<div class=’thread’ id=’thread”+threadid+”‘ style=’height:”+ threadHeight +”;left:”+left+”;font-size:”+ curFontSize +”;z-index:”+ curFontSize+”;opacity:”+opacity+”;’>”+ startDigit +”</div>”);
animateThread(threadid,startDigit,curFontSize);
threadid++;
threadCount++;
}
function animateThread(tid,sd,cfz){
var nextDigit = Math.floor((Math.random()*10));
$(‘#thread’+tid).prepend(nextDigit + ‘<br/>’);
setTimeout(function(){
animateThread(tid,sd,cfz);
}, animateThreadSpeed);
}
function removeThread(){
moveDownThread(removeThreadId);
threadCount–;
setTimeout(removeThread, threadRemoveSpeed);
}
function moveDownThread(tid){
$(‘thread’ + tid).animate({
top : winH
}, threadRemoveSpeed, function(){
$(‘#thread’+ tid).hide();
setTimeout(startAnimation, threadAddSpeed);
});
}
function zoomInTitle(){
if(titleFontSize <=100){
$(‘#logo’).css(‘font-size’,titleFontSize);
$(‘#logo’).css(‘z-index’,titleFontSize/10);
$(‘#logo’).css(‘opacity’,titleFontSize/100);
titleFontSize++;
if(titleFontSize == 100){
$(‘#logo’).fadeOut(5000);
}
setTimeout(zoomInTitle, 100);
}
}
</script>
</head>
<body style=”padding:0;margin:0;”>
<div id=”page” align=”center”><div id=”logo”>PROWARENESS</div></div>
</body>
</html>

 

 

Category: PHP  | 2 Comments
Author:
Monday, February 04th, 2013

Sorting multi dimensional arrays

There are functions to sort an array of values in a single dimensional array but what if the array is a multi dimensional array and it is to be sorted at a depth of 3 or 4 or higher with a combination of multiple values.

Below is an array of employees and their details ..

$arr = array();
$arr[0] = array(
‘empinfo’ => array(‘fname’=>’sat’, ‘lname’=>’kum’),
‘emphobbies’ => array(‘cricket’,'photography’),
‘empmanagers’ => array(1 => array(‘ManagerName’ => ‘sam’), 22, 3, 13)
);
$arr[1] = array(
‘empinfo’ => array(‘fname’=>’sat’, ‘lname’=>’siy’),
‘emphobbies’ => array(‘chess’,'photography’),
‘empmanagers’ => array(1, 22, 3, 13)
);
$arr[2] = array(
‘empinfo’ => array(‘fname’=>’nav’, ‘lname’=>’bab’),
‘emphobbies’ => array(‘cricket’,'photography’),
‘empmanagers’ => array(1, 22, 3, 13)
);
$arr[3] = array(
‘empinfo’ => array(‘fname’=>’kar’, ‘lname’=>’sha’),
‘emphobbies’ => array(‘cricket’,'photography’),
‘empmanagers’ => array(1, 22, 3, 13)
);
$arr[4] = array(
‘empinfo’ => array(‘fname’=>’vik’, ‘lname’=>’kum’),
‘emphobbies’ => array(‘cricket’,'photography’),
‘empmanagers’ => array(1, 22, 3, 13)
);
$arr[5] = array(
‘empinfo’ => array(‘fname’=>’els’, ‘lname’=>’ver’),
‘emphobbies’ => array(‘cricket’,'photography’),
‘empmanagers’ => array(1, 22, 3, 13)
);
Now, say if the array is to be sorted based on first name and lastname combination… below is the code for implementing this (using a single for loop).
$check = count($arr)-1;
for($i=0; $i < $check; $i++)

{

                // values to be compared

               $v1 = $arr[$i]['empinfo']['fname'] .” “. $arr[$i]['empinfo']['lname'];
               $v2 = $arr[$i+1]['empinfo']['fname'] .” “. $arr[$i+1]['empinfo']['lname'];

               // change the sort order by changing the below if condition
               if($v1 > $v2)

               {
                              swap($arr[$i],$arr[$i+1]);
               }

               // reinitialize the pointer
               if($i+1 == $check)

               {
                              $i = -1;
                              $check–;
               }
}

// Helper function for swapping the values
function swap(&$x,&$y)

{
               $d = $x;
               $x = $y;
               $y = $d;
}

The above code can be used to sort a multi dimensional array of any depth and with any combination (like firstname + lastname + surname ….). Only thing to be done is to change the values to be compared inside the for loop.

Category: PHP  | Leave a Comment
Author:
Monday, February 04th, 2013

For all those developers who are having work on creating images or modifying them, there is a tool for helping you…

No need to install any app on your machine or no need to purchase license .. it is an online tool and is completely free.

www.pixlr.com

This is like a photoshop tool with basic features. Give a try and you will be finding it useful.

Category: PHP  | Leave a Comment
Author:
Monday, February 04th, 2013

Git is an alternate system just like another version control systems (SVN, CVS) and is a command line tool with an ease of using.

Here are few reasons to prefer GIT over other versioning tools  …

1. GIT is also an opensource like other tools.

2. GIT is a fully distributed version control system and can allow you to work even offline for most of the operations like checking the history, checking the differences and commiting the changes.

3. Fast when compared to other versioning systems. Fast at a difference of around 3 seconds.

4. Easy to merge the changes made by multiple users with the provided web GUI by just clicking the “Merge changes” button.

5. Changes made by the users are easy to track with the web GUI provided and even see the differences.

If you guys are interested in trying this… here is the download link http://git-scm.com/download

For more details and creating your own repositories… here is the link https://github.com/

Here are the steps for installation : http://git-scm.com/book/en/Getting-Started-Installing-Git

Hope this could be helpful…

 

Category: PHP  | Leave a Comment
Author:
Monday, January 14th, 2013

Imagine you are building a huge web application. Each time you change the code , you need to test each and every scenario. What if  you have the script that automatically test’s each scenario.

Yes you can do that using functional testing.

Symfony  has sfBrowser class, that acts like a browser ,connected to symfony and it does not require any web server.

sfBrowser object has methods like navigation in browsers.

  • gett()   : Get a URL
  • post()  :Posts to a URL
  • call()   : Calls URL
  • click() :  Click a link

etc

A Example Code would look like this

$browser = new sfTestFunctional(new sfBrowser());
//Login Success Case


$browser
->info('Login Success Case')
->call('/', 'POST', array('user_name' => 'your_username', 'password' => 'your_password', 'language'=> 'en', 'submit'=> 'Login'))
->with('request')->begin()
->isParameter('module', 'login')
->isParameter('action', 'index')
->end()
->with('response')->begin()
->isStatusCode(302)
->isRedirected() // Check that the response is a redirect
->followRedirect() // Manually follow the redirection


->isStatusCode(302)
->end()

What this code does is ,it checks for the LOGIN module.  The isParameter checks the request Parameter Value. So in the Above case we are checking for the module ‘login’ and the action method is ‘index’.

Then we check for the Status code 302 using isStatusCode and then  check if the response is Redirected using isRedirected()

How to run this Test?

ftpass

 

 

 

 

 

 

 

So this Functional test passed.

Lets make this Test Fail now.


$browser = new sfTestFunctional(new sfBrowser());
//Login Success Case


$browser
->info('Login Success Case')
->call('/', 'POST', array('user_name' => 'your_username', 'password' => 'your_password', 'language'=> 'en', 'submit'=> 'Login'))
->with('request')->begin()
->isParameter('module', 'login')
->isParameter('action', 'index')
->end()
->with('response')->begin()
->isStatusCode(200)
->isRedirected() // Check that the response is a redirect
->followRedirect() // Manually follow the redirection


->isStatusCode(302)
->end()

 

I am changing the isStatusCode to 200 to make this test fail

ftfail

 

 

 

 

 

 

 

You can run all the test at once and check the details statistics

php symfony test:functional frontend

alltest

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Category: PHP  | Leave a Comment
Author:
Thursday, December 13th, 2012

There is so much talk going about mvc frameworks in php. Let me demo one simple framework using smarty and real world sample of user login.

In this framework all incoming requests are routed to index.php which sets up the enviroment and routes the control to Server.php

index.php code

<?php
/*
PHP ERROR REPORTING LEVEL
By default runs with error reporting set to ALL. For security
reasons you are encouraged to change this when your site goes live.
For more info visit: http://www.php.net/error_reporting
*/
error_reporting(0);
ini_set("display_errors",0);
/*
APP FOLDER NAME
This variable must contain the name of your "app" folder.
Include the path if the folder is not in the same directory
as this file.
NO TRAILING SLASH!
*/
$app_folder = "app";
define('EXT', '.php');
define('FCPATH', __FILE__);
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('BASEPATH', $app_folder.'/');
$api_folder = 'api';
define('APIPATH', BASEPATH.$api_folder.'/');
/*
LOAD THE FRONT CONTROLLER
And away we go...
*/
require_once APIPATH.'Server.php';
?>

Our Sample server.php code loads the model as shown

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
require(BASEPATH.'config/Constants.php');
require(CONFIG.'Config.php');
require(COMMON.'Dbi.php');
require(UTILS.'Common.php');
function load_model($c,$m){
if(isset($c)){
foreach($_REQUEST as $k=>$v){
$_REQUEST[$k]= strip_tags(addslashes($v));
}
$session_not_required=array("User.getLandingPage","User.login","User.register");
if(in_array($_REQUEST['do'],$session_not_required) && !isset($_SESSION['user'])){
$arr = array('path' => MODEL, 'prefix' => 'm', 'class' => $c, 'params' => $_REQUEST, 'ui' => "desktop");
$model = loadClass($arr);
if(isset($model) && !empty($model)){
$arr = array($_REQUEST);
if(method_exists($model,$m)){
$model->$m($arr);
}
}
}elseif(isset($_SESSION['user'])){
if($m == 'getLandingPage') $m = 'getDashBoard';
$arr = array('path' => MODEL, 'prefix' => 'm', 'class' => $c, 'params' => $_REQUEST, 'ui' => "desktop");
$model = loadClass($arr);
if(isset($model) && !empty($model)){
$arr = array($_REQUEST);
if(method_exists($model,$m)){
$model->$m($arr);
}
}
} else {
header("Location:$base_url?do=User.getLandingPage");
}
}
}
if(!isset($_REQUEST['do']))
$_REQUEST['do'] = "User.getLandingPage";
$cl_meth = explode(".",$_REQUEST['do']);
load_model($cl_meth[0],$cl_meth[1]);
?>

User model class includes the Profile controller to do db operations and passes the control to smarty templates for final display

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once(CONTROLLER.'Profile.php');
class mUser {
private $log = NULL;
public function __construct($arr) {
$_REQUEST = $arr;
}
public function &getLandingPage(){
$smarty = getSmarty();
$smarty->display("index.tpl");
}
public function &register(){
$profile = new Profile($_REQUEST['params']);
$rsp = $profile->registerProfile($_REQUEST['params']);
//print_r($rsp);
print(json_encode($rsp));
exit;
}
public function &login(){
$profile = new Profile($_REQUEST['params']);
$rsp = $profile->loginUser($_REQUEST['params']);
print(json_encode($rsp));
exit;
}
public function &getDashBoard(){
$smarty = getSmarty();
$smarty->display("dash.tpl");
}
public function &logout(){
unset($_SESSION['user']);
header("Location: index.php");
}

Profile Controller connects to db to do authentication and send a return value as ok or error

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Profile {
private $p;
public function __construct($arr = NULL) {
if(isset($arr) && is_array($arr) && isset($arr['params'])){
$this->p = $arr['params'];
}
}
public function genPwd(){
return rand(123456,126789);
}
public function registerProfile($p){
$db = Db::getDbInstance(getConfigItem('database'));
$q = array();
$user = $p['uname'];
$email = $p['uemail'];
$passwd = $this->genPwd();
$sql = "insert into users(name,email,password,date) values('$user','$email', '$passwd',now())";
$result = $db->do_sql($sql);
$eid = mysql_insert_id();
if($eid){
$rsp = array(
'RetVal' => 'ok',
'Rsp' => array('eid' => $eid, 'Message' => $msg)
);
}else{
$rsp = array(
'RetVal' => 'error',
'Rsp' => array('Message' => 'User email already exists')
);
}
return $rsp;
}
public function loginUser($p){
$db = Db::getDbInstance(getConfigItem('database'));
$q = array();
$email = $p['uemail'];
$passwd = $p['upass'];
$sql = "select * from users where email = '$email' and password = '$passwd'";
$result = $db->do_select($sql);
if($result[0]){
$_SESSION['user'] = $result[0];
$rsp = array(
'RetVal' => 'ok',
'Rsp' => array('eid' => $result[0]['uid'], 'Message' => 'Login success')
);
}else{
$rsp = array(
'RetVal' => 'error',
'Rsp' => array('Message' => 'Incorrect Credentials')
);
}
return $rsp;
}
}

Our folder structure will be like as shown below

Thats it for the simple mvc example. You can keep adding classes in model and have a request method like Profile.editUser, Profile.updateUser etc and have appropriate templates in view folder. You can download simple-php-framework here

Category: PHP  | Leave a Comment
Author:
Thursday, December 13th, 2012

Setting up virtual hosts on Linux (Ubuntu) – for LAMP stack

After installing LAMP (apache, php) stack on ubuntu, we can setup multiple projects inside the file system (/var/www) and we can access each project from browser like http://localhost/projectname/public/index.php

Don’t you think it is a bit tough to type the whole path everytime and also not so pretty… How good it will be if you access the above path with a short name like projectname.localhost or www.projectname.com or just projectname

Lets see how we can do this. To make you understand better I would like to explain you with two projects.
Say.. you want to create two projects.. pone and ptwo.

First steps first.

1. Open the terminal.
2. Navigate to /var/www (using the command >> cd /var/www)
3. Create project folders pone and ptwo (command >> sudo mkdir pone)(repeat same for ptwo)
4. Enter your desktop password if prompted
5. Give full permissions on this folder (sudo chmod 777 -R pone)(repeat same for ptwo)(not mandatory)

So now your pone and ptwo projects are created.

6. From terminal navigate to the folder where your configurations are stored. (command >> cd /etc/apache2/)

Here you find few folders like sites-available, sites-enabled and so… These are the ones we will be using next.
We will do for the project pone here and you can repeat the same steps for ptwo.

7. Now, go into the folder sites-available (command >> cd sites-available)
8. This folder may be having a default file and you have to create your new file here, leaving the default. (sudo nano pone.localhost)
9. This opens a new editor. Type your virtual host code here

<VirtualHost *:80>

ServerName www.pone.com

DocumentRoot /var/www/pone
<Directory /var/www/pone>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

</VirtualHost>

and save the file.

From the above we are setting the documentroot as “/var/www/pone” assuming the project’s starting file is inside this folder and as index.php. If you are using any mvc frameworks it might be like “/var/www/pone/public/index.php” depending on the framework structure.
From the above you are defining servername as www.pone.com . This is the one you will be using for accessing pone project from the browser, but not yet. :)

10. Save the file (ctrl x) and ‘Y’ if prompted for yes or no. or click ENTER if it shows the filename which you created and says save it to this file ?
11. Next from the terminal we need to enable this site. If you go into the folder sites-enabled , it wont be having your enabled pone.localhost file. To enable it run the command “sudo a2ensite pone.localhost“. Before running this command, make sure that you are inside sites-available.
12. After the command is executed.. a file with same name “pone.localhost” created inside sites-enabled folder.
13. Restart the apache server now. (sudo /etc/init.d/apache2 restart) (Mandatory to restart)

The virtual host is setup now. But still you may not be able to access the pone from browser with www.pone.com . Becos the browser is not informed to check the local apache server if someone tries to acces www.pone.com

14. Again go to terminal and navigate to /etc (cd /etc)
15. Open the file hosts (sudo nano hosts).
16. Add

               127.0.0.1       www.pone.com

at the end of the page and save the file. The serverName given in the virtual host above should match with  www.pone.com from the above line
Thats it ! now try www.pone.com from your browser and it should load your project.

 

Category: PHP  | Leave a Comment