Monday, September 1, 2008

Remote Debugging with xDebug


Debugging is an important fact in programming as it is used to find errors and malfunctions in programming. xDebug is a powerful tool to enable server side remote debugging. XDebug latest version can be downloaded from
http://www.xdebug.org/

Windows users can directly download the dll file and Linux users can download the source and compile.

By putting the following two lines in the php.ini will enable debugging

zend_extension_ts="/path_to_the_module/php_xdebug-2.0.3-5.2.5.so"
xdebug.remote_enable=1

Have fun!

Chain-of-Command pattern


Chain of Command handler is very important when it comes to loose coupling systems where change of a one module should not effect others if not necessary. As the name implies the Chain of Command pattern will accepts commands and arguments and is chained through the class until the command is executed. If the process can execute the command it will execute the command and stops. Like wise each handler class will decide whether it can handle the request or not.
interface ICommand
{
function executeCommand($command_name, $params);
}

class ChainOfCommands
{
private $mycommands = array();

public function addCommands($cmd)
{
$this->mycommands[]= $cmd;
}

public function runCommand($command_name, $params)
{
foreach( $this->mycommands as $cmd )
{
if ( $cmd->executeCommand($command_name, $params) )
return;
}
}
}
each handler class should implement the ICommand interface and override its onCommand method
class HelloCommand implements ICommand
{
public function executeCommand($command_name, $params)
{
//Check the command name
if ( $command_name!= 'Hello_Command' )
return ;

echo( "Inside Hello Command" );
// Put all the code to be executed and error handling
return true;
}
}
now create instances of ChainOfCommands class , add required commands and call the executeCommand method
$obj = new ChainOfCommands();
$obj->addCommand( new HelloCommand() );
$obj->runCommand( 'Hello_Command', "param 1" );

Implement Singleton pattern with PHP 5


We always create multiple instances of a class when we do programming but sometimes it is necessary to restrict people to create more than one instance of a class and this is where singleton comes into play.


Singleton classes use a static function to return its instance so that no matter how many object created in the class it uses the same object reference i.e all the instances share the same reference (because of the behavior of static)

ex -

public static function getObject()
{
if(!isset(self::$instance))
{
$object= __CLASS__;
self::$instance=new $object;
}

return self::$instance;
}

we can call this method MyClass::getObject(); if the class name is MyClass