fritz!box call monitor with node.js

After two years: A new post. Yay!

The fritz!box has an integrated call monitor that can be activated by dialling #96*5* (and deactivated by #96*4* …). With just a few lines of code we can use node.js to build a small TCP client:

var net = require('net');
var sys = require('sys');
 
var client = net.createConnection(1012, "192.168.2.1");
 
client.addListener("data", function (chunk) {
	sys.puts(JSON.stringify(chunk));
});
client.addListener("end", function () {
	client.end();
});

BlogDesk?

Trying BlogDesk for posting …

Singleton Design Pattern

Issue no. 3 on design patterns: The singleton pattern.

Whenever we need a place to save and retrieve data throughout a script without using globals the singleton pattern comes in handy. It allows only one instance of itself. What seems like a drawback is quite useful: Wherever in your source you instantiate such an object: You can be sure that you’ll always get the instance of the same object. Remember the parameterized factory from the last chapter? Every time we wanted to create a new database-access-object we had to pass “mysql” or “pgsql” to the create-method. Wouldn’t it be easier if we just saved the database type to a singleton and retrieved it everytime we need it?

//------------------------------------------------
// Singleton
//------------------------------------------------
// Definition
class Singleton
{
	// "This is a handle to myself"
	private static $instance;
 
	// database type
	public $dbtype = "";
 
	// Private clone-function and private constructor 
	// make sure, that nobody can clone the object or
	// instantiate it using the standard constructor.
	private function __construct() {}
	private function __clone() {}
 
	// This one returns the instance handle to itself.
	// It's static, because it has to be accessible
	// before any object is available
	public static function GetInstance()
	{
		// "Am I already existing?"
		if (!isset(self::$instance))
		{
			// "No? Create myself and save the handle
			// to myself."
			$class = __CLASS__;
			self::$instance = new $class;
		}
 
		// "Return handle to mysqlf"
		return self::$instance;
	}
}
 
// ...
// somewhere in our code
function SetupScript()
{
	// Get handle to our singleton object
	$GlobalInfos = Singleton::GetInstance();
	// Set the $content variable to 42 
	$GlobalInfos->dbtype = "mysql";
}
 
// ...
// somewhere else in our code
SetupScript();
 
// ... deep down in the code
// Get handle to our singleton object
$Registry = Singleton::GetInstance();
// Remeber that from the last chapter?
$myDbObj= MyClassFactory::Create($Registry->dbtype);

Parameterized Factory Desing Pattern

The parameterized factory design pattern is an extension to the factory design pattern as you might have guessed, but here we can make the factory create different objects depending on the parameter passed to the create-method. Imagine your application is supposed to connect to a MySQL-DB or to a PostgreSQL-DB. Instead of creating different objects in your code you might just want to pass “mysql” or “pgsql” to the create-method and you get the class needed for the specific database.

//------------------------------------------------
// Parameterized Factory
//------------------------------------------------
// Definition
class DbMySQL
{
	public $content= "I am MySQL!\n";
}

class DbPgSQL
{
	public $content= "I am PostgreSQL!\n";
}

class DbFactory
{
	public function Create($dbtype)
	{
		switch($dbtype)
		{
			case "mysql":
				return new DbMySQL();
				break;
			case "pgsql":
				return new DbPgSQL();
				break;
		}
	}
}

// Usage
$myFirstObj= MyClassFactory::Create("mysql");
$mySecondObj= MyClassFactory::Create("pgsql");
echo $myFirstObj->content; // "I am MySQL!"
echo $mySecondObj->content; // "I am PostgreSQL!"

Factory Design Pattern

Design Patters part 1.

I built these samples on PHP design patterns a while ago to make some friends write better code. They ignored it, so I give it to you. I hope they are self-explanatory. If not: Feel free to ask!

First off: The factory design pattern. It encapsulates the creation of a class so an object can be instantiated using the factory’s create-method rather than the class’ constructor. This comes in handy if you’re planning to extend your application (usually you are) and don’t want to change every call to your class’ constructor.

//------------------------------------------------
// Factory: The "factory pattern" creates an object
// using a method rather than a constructor
//------------------------------------------------
// Definition
class MyClass
{
	public $content = "Hello world!\n";
}

class MyClassFactory
{
	public function Create()
	{
		return new MyClass();
	}
}

// Usage
$myObject= MyClassFactory::Create();
echo $myObject->content; // "Hello world!"

BLAZEserver

Introducing BLAZEserver. Get it HERE!

Debugging on local Apache with PhpED

I’ve been working with PhpED for quite some time, but now that I’m using the Zend Framework I reached the point, where the integrated server isn’t good enough anymore. The main concern was mod_rewrite. I needed a way to debug on my local Apache installation (XAMPP to be specific).

I fought my way through multiple blogs and forums to get it all up and running. Here are my condensed facts for Apache and PhpED on Windows XP. This might be a little bit too detailed. If you think “Man, I really want to debug on my local Apache” you’ll probably know how to add extensions to your PHP environment, but I’ll tell you anyway:

Getting the debugger extension

PhpED comes with a variety of debugger extensions. They can be found in a subdirectory of your PhpED installation. For me that’s

c:\Program Files\phped\debugger\server\Win32\x86

Here we have extensions for different versions of PHP. I chose

php_dbg.dll-5.2.x

Where to put the extension now?

Make yourself a quick and dirty phpinfo.php file and put it in your project root.

<?php
   phpinfo();
?>

Open your project in your browser (Time for me to recommend a vhost once more). It’s really important that you don’t start that file from PhpED since it’ll use it’s own PHP environment and that’s exactly what we want to avoid. Now look for the extension_dir entry in the Configuration > PHP Core section. It should say something like

C:\xampp\php\ext\

Now get your php_dbg.dll-5.2.x and put it into your extension_dir. Trim the version information. What’s left will be

php_dbg.dll

Telling PHP what to do

Go back to your browser and go to the top of your phpinfo page. Look for the php.ini in use (Loaded Configuration File) and open it in the editor of your choice (I guess it’ll be PhpED, right?). Scroll down (or search for) the section named Dynamic Extensions. Add a new line:

extension=php_dbg.dll

Next we’ll configure the debugger. At the end of your php.ini add the following:

[debugger]
debugger.enabled=on
debugger.profiler_enabled=on
debugger.hosts_allow=ALL
;debugger.hosts_deny=ALL
debugger.ports=7869, 10000/16

This might be a little bit risky. I don’t have to share my development environment with other people and my system isn’t reachable from the outside world. You might want to have a closer look at debugger.hosts_allow. If you want to play it safe, uncomment the debugger.hosts_deny entry to block everyone, then add your allowed hosts to debugger.hosts_allow.

Restart your Apache. Go back to your browser and hit refresh. Next to the Zend Engine 2 logo you should see something like “with DBG v3.1.11, (C) 2000,2007, by Dmitri Dmitrienko”. If you see it: You’re almost done. If you don’t see it: You probably changed the wrong php.ini.

Setting up your project in PhpED

Open PhpED and go to your project properties. In the Mapping section change Run mode to HTTP Mode (3rd party WEB server) and let the Root URL point to your project server.

Basically that’s it!

Troubleshooting

I had some problems when debugging the first times. Apache crashed with an Windows exception once the page started loading. Try the following: Go back to your php.ini and search for [Zend]. If you don’t know, if you need these settings, then you probably won’t. Try to go without them by commenting them.

[Zend]
;zend_extension_ts = "C:\xampp\php\zendOptimizer\lib\ZendExtensionManager.dll"
;zend_extension_manager.optimizer_ts = "C:\xampp\php\zendOptimizer\lib\Optimizer"
;zend_optimizer.enable_loader = 0
;zend_optimizer.optimization_level=15
;zend_optimizer.license_path =
; Local Variables:
; tab-width: 4
; End:

Restart your Apache after you’re done!

Sources

NuSphere support forum
Darren Beals blog
PHPEclipse forum

Zend Tutorial

I’ve been trying to set up my directories on the production server yesterday. Meanwhile I came across Rob Allen’s Blog. It features a nice tutorial including database access and forms. Rob doesn’t waste time doing it the “easy” way, like the Zend framework quick start tutorial does. You get your full load of class inheritance right away. Another useful link is the Zend framework multimedia section, especially the screencasts by Mitchell Hashimoto.

To bad I had to realize, that the framework wasn’t able to load a file named ReflectionClass.php. Even worse: After doing some reflection myself I figured out, that it wasn’t a framework issue: ReflectionClass was meant to be the actual PHP class, but since my provider has the reflection API disabled, the framework tried to instantiate it, failed and tried to find a file of that name instead. I really hope, they’ll fix that soon. (I know they will)

So instead I had to overhaul my XAMPP, which was quite easy, once I figured out how to do it. Well, here are my hints to get the Zend framework running on your raw XAMPP installation:

  • Be sure to activate mod_rewrite in your conf/httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so
  • You might want to create a virtual host for your project in conf/extra/httpd.vhosts.conf pointing towards the public directory of your project
<VirtualHost *:80>
    ServerAdmin aaa@bbb.de
    DocumentRoot c:\htdocs\myproject\public
    ServerName myproject.localhost
</VirtualHost>
  • If you do so, you should edit your hosts.txt (wherever it may be on your OS)

Have fun working it out!

Frameworks

After trying to rewrite my code using design patterns till 4:20 a.m. I thought, that someone already might have built a working collection of classes to do the same thing. It’s important to understand how design patterns work and why and where they can help you simplifying things, but hey: I wan’t to build a scalable web application and I don’t really want to spend my free time building my own framework.

I’ve been flipping through Duane O’Brien’s article on PHP frameworks for a while now and decided to give the Zend Framework a try.