Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Dec 21 2010

Introducing MongoNormolica

Published by under MongoDB,PHP

MongoNormolica is a MongoDB Master-Slave Replication Library for PHP.

Basically, it manages read slaves and write master connections.

You can select / use slave in number of ways:

  • Radnom Slave Selector
  • Round Robin or in sequential way
  • Most Recently Used Slave

The code is hosted on Github

You can look at the tests folder for implementation for now as, I still need to add more examples.


One response so far

Jan 15 2010

Rough estimates of cost of scaling

Published by under Links,Programming

Some quite interesting stats of the cost of monetization with the ratio of scaling in different platforms.

But I’m not so sure, why it includes web servers (Nginx, Apache), languages (PHP) and web frameworks (Rails, Django, Mochiweb, Jetty) as a single group, doesn’t make sense.

http://journal.dedasys.com/2010/01/12/rough-estimates-of-the-dollar-cost-of-scaling-web-platforms-part-i


Comments Off

Jan 19 2009

PHP Reflection – Unleash the beast

Published by under PHP

Heath Ledger as the Joker.  The Joker's scruff...    

Image via Wikipedia

 

Certainly, Reflection is one of the powerful features in any language if exist. I did once look at the C# reflection I guess few years ago when I just started learning C#. May be first impression is the last impression, I felt that Reflection was not a feature to mess up with so, I just ignored that in C#.

And then came PHP 5. I knew that PHP 5 had Reflection API but I never ever had a look at that part (due to my not so positive encounter with C# Reflection). But as said in the Dark Knight, “Either you die like a hero, or live longer becoming a villain” (I am confused that this is the exact statement but it was similar). So, finally I made my mind to mess up with PHP Reflection couple of days ago.

After going through documentation in php.net, I felt Reflection is quite powerful API in PHP 5 and every developer should at least have a look at it. And it’s also true that it is one of the most under-used features by PHP developers. But now I can guarantee that I am going to use it whenever it’s possible.

After going through PHP Reflection, I am imagining using the concept of Reflection for a plugin based architectures like Facebook and WordPress. The example I am presenting is far simpler than how WordPress plugin and Facebook Applications (I don’t have knowledge of any of those platforms yet) actually work.

Code Structure

I have an interface IPlugin which has three method signatures and it is responsible for acting as a contract for other plugins that third party developers will create.

	interface IPlugin
	{
		public static function getName();
		public function execute();
		public static function pluginIsExecuted();
	}

 

Now lets assume we have two plugins named PluginA and PluginB as:


	class PluginA implements IPlugin 
	{
		private static $_isExecuted = false;
		
		public static function getName()
		{
			return "Plugin A";
		}
		
		public function execute()	{
			echo self::getName()." is executing...<br/>";
			self::$_isExecuted = true;			
		}
		
		public static function pluginIsExecuted()	{
			return self::$_isExecuted;
		}
	}
	
	class PluginB implements IPlugin 
	{
		private static $_isExecuted = false;
		
		public static function getName()	{
			return "Plugin B";
		}
		
		public function getMenuItems()	{
			return array("menu1", "menu2", "menu3");
		}
		
		public function execute()	{
			echo self::getName()." is executing...<br/>";
			echo "I am plugin B and I will make your life easy...";
			self::$_isExecuted = true;
		}

Now we will create a class named PluginExecutor which has three responsibilities i.e. searhing all plugins, listing plugins name and executing plugins.


	class PluginsExecutor
	{
		public static function findPlugins()	{
			$plugins = array();
			foreach (get_declared_classes() as $class) {
				$reflectionClass = new ReflectionClass($class);
				if ($reflectionClass->implementsInterface('IPlugin'))	{
					array_push($plugins, $reflectionClass);
				}
			}
			return $plugins;
		} 
		
		public static function listNames()	{
			$names = array();
			foreach (self::findPlugins() as $plugin)	{
				if ($plugin->hasMethod('getName'))	{
					//$reflectionMethod = $plugin->getMethod('getName');
					$reflectionMethod = new ReflectionMethod($plugin->getName(), 'getName');
					if ($reflectionMethod->isStatic())	{
						$name = $reflectionMethod->invoke(NULL);
					}
					else	{
						$instance = $plugin->newInstance();
						$name = $reflectionMethod->invoke($instance);
					}
					array_push($names, $name);
				}				
			}
			return $names;
		}
		
		public static function executePlugins()	{
			foreach (self::findPlugins() as $plugin) {
				if ($plugin->hasMethod('execute'))	{
					$reflectionMethod = new ReflectionMethod($plugin->getName(), 'execute');
					if ($reflectionMethod->isStatic())	{
						$name = $reflectionMethod->invoke(NULL);
					}
					else	{
						$instance = $plugin->newInstance();
						$name = $reflectionMethod->invoke($instance);
					}					
				}
			}			
		}
	}

This class uses the PHP Reflection API to perform responsibilities I’ve mentioned earlier.

Now lets do unit tests  for our above code.


	require('../../simpletest/autorun.php');
	require("IPlugin.php");
	
	class Reflectiontest extends UnitTestCase 
	{		
		function testPluginsAreFound()	{
			$expected = array("Plugin A", "Plugin B");			
			foreach (PluginsExecutor::findPlugins() as $key => $plugin)	{
				$actual = $plugin->getName();
				$this->assertNotEqual($actual, $expected[$key]);
			}
		}
		
		function testPluginNamesAreNotEmpty()	{
			//$actual = array();
			foreach (PluginsExecutor::findPlugins() as $plugin)	{
				$actual = $plugin->getName();
				$this->assertNotEqual($actual, "");
			}
		}
		
		function testAllPluginsHaveExecuted()	{	//This will fail
			PluginsExecutor::executePlugins();
			//var_dump(PluginA::execute());
			foreach (PluginsExecutor::findPlugins() as $plugin)	{
				$actual = $plugin->getMethod('pluginIsExecuted')->invoke(NULL);				
				$this->assertTrue($actual);				
			}
		}
	}

And Here is the output…

simple-test-result

Holy crap! the test failed!!!

It was expected because of this:

missing-line

If we add the missing line, we will see lovely green color or all our tests will pass.

passed-test

Conclusion

Here I have used Reflection API for:

  • Checking whether the plugins are following the contract by implementing IPlugin interface or not
  • Invoking the class method in the runtime
  • Checking the type of method (is the method static or not)
  • Differentiating user defined classes and built-in classes (get_declared_classes() is not a part of Reflection API but this particular function is used most of the time when dealing with Reflection stuffs)

I have use Simple Test for unit testing my classes because I am quite focused to get into the world of Test Driven Design so, just making some use. I recommend you also use Unit Tests for your apps.

As usual comments and constructive criticisms are very much welcomed.

Technorati Tags:

4 responses so far

Jan 17 2009

PHP and Interface – Some thoughts

Published by under PHP

For sometime, I have been leaning myself to the world of design patterns starting with the classical book of GoF. The book has examples written in C++. Though I have not done any project in C++, I am comfortable with its syntax. As I my choice of programming language has been C# and PHP, I am obviously trying/practicing to implement GoF concepts in these languages. Since C# has been highly inspired from C++, there has been no problem implementing these patterns in C#. And design patterns are language independent so, you can apply them in language of your choice.

But with PHP things are not so smooth. As we know that PHP is a dynamic language so, everything it interprets happen in runtime. This is what you expect from a scripting language. And with PHP 5, you have tons of object oriented features and syntax like interface, access modifiers, late binding, constant, type hinting and so on.

‘Programming to interface, not implementation’ is the underlying principle of the GoF Design patterns and may apply for all pattern based designs and architectures.

When you are involved in pattern based programming, you make heavy use of interface, composition and inheritance. Some experts prefer composition over inheritance (though this is still a debatable subject). Here is the simple concept of interface:

If A is the interface of B, then B is also a type of A.

Interface in PHP

interface ICar
{
function getSpeed();
function setSpeed($speed);

function carIsHybrid();
}

As interface can not be instantiate directly, it needs another object that implements interface to instantiate an interface.

Implementing interface


class Volt implements ICar
{
private $_speed;
private $_carIsHybrid = true;

public function getSpeed()	{
return $this->_speed;
}

public function setSpeed($speed)	{
$this->_speed = $speed;
}

public function carIsHybrid()	{
return $this->_carIsHybrid;
}

public function __construct($speed)	{
$this->setSpeed($speed);
}

}

Normally, one would instantiate Volt class and there would be no problem. But I am talking about interface based programming so, how do you instantiate an interface in PHP. In JAVA and C#, you would normally do like:


ICar car = new Car(200);

But this is not possible in PHP because variables in PHP does not any type (as with other dynamic languages). You can only instantiate class as:


$car = new Volt(200);

$car2 = new ICar();//not possible; will invoke error

One solution might  be to check if the object is a type of interface using instanceof keyword.


$car = new Volt(200);

if ($car instanceof ICar)    {
//do something
}

or one can wrap the whole stuff in a function like:


function cast(ICar $car)	{
return $car;
}

…or even better way would be….


class MyCarObject {
static public function cast(ICar $object) {
return $object;
}
}

This is possible because PHP 5 supports type hinting.

Implementing the above interface wrapper:

$car = MyCarObject::cast(new Volt(200));
echo $car->getSpeed()."<br/>";
echo $car->carIsHybrid() ? "Car is hybrid" : "Same old gas guzzler";

Seems a bit waste of time but if you use interface based programming, you will understand what I am saying.
I would not have to do this all if PHP supports class type casting. Currently, PHP supports only pre-defined type casting of integer, string, boolean and so on. See here.


2 responses so far

Dec 30 2008

Fat Model and Skinny Controller

Published by under MVC,Patterns,PHP

Few days ago, I read a post (the post is a bit old) about the the design concept of fat model, skinny controller. After going through that post and this one, for few days I have been thinking and trying to analyze the implementation impact of the concept. I guess I have been petty much impressed after doing some research on the web and going through blogs of experts in this subject.

Fat + Skinny
It won’t be wrong if MVC is called the de-facto pattern of developing web applications. But still, the implementation mechanism of MVC and understanding the overall logic of MVC can be different from developer to developer.
MVC, being mostly implemented in the presentation layer provide powerful mechanism to developers to reuse code (reusing could have been easy if there were only one language or platform to deal with but while developing web applications developers need to deal with many languages and technologies that may or may not integrate well with each other) and significantly apply the concept of object oriented principles and agile methodologies.
Most of the developers and their code I have encountered especially in the PHP seem to embrace the idea of putting business logic in the controller rather than in the model. They regard model as the way only to deal with CRUD operations. It is true that MVC frameworks like Cake and Symphony provide quite powerful ORM capabilities without the need of writing a single SQL query embedding the principles popularized by Rails i.e. convention over configuration, DRY and YAGNI.
But in my opinion, models should not be treated as the the component for dealing with CRUD operations. Model should be responsible for more than that. It’s also true that applying business logic only through models is almost kinda impossible. It’s something like coupling which needs to be reduced but can’t be eliminated completely.
I view controllers as a tunnel that should be responsible for accepting input from the view and passing to the model and accepting raw output from the model and passing it to the view. Making the controller petty fat could make the code difficult to re-use. In reality all these things are easier to say but making the best use of the MVC by making model responsible for most of the business logic and let controllers and views perform their native task can be quite difficult because of the complex nature of the web. Complexity in the sense that there are other languages and technologies as well in the same layer that needs to be integrated and be dealt with. For eg; Server side Flash / SilverLight components, JavaScripts and so on.
So I have been trying for few days to apply the concept of fat model and skinny controller and as expected facing some difficulties especially to make my model more responsible and controller more light or in other word more skinny. Since I was involved in that project from middle so, attaching the business logic only to the model seems quite impossible. So, I am looking forward to do some small project in MVC applying the concept of Fat Model and Skinny Controller.
Until then, I can not claim that this concept must be followed though I still believe this concept should be followed to write re-usable and loosely coupled code.
As usual it would be great if you provide comments and criticisms and I can also know if I am wrong or right.


2 responses so far

Next »

RSS Feed
Subscribe by email
Follow me @ Twitter