doit, doit now!

doing stuff in a place

Daemons in PHP

Filed under: Geek Out, PHP — Nick Hodulik at 9:45 pm on Monday, August 1, 2005

I have been writing a daemon (Unix-speak for “server program,” like a Web server or mail server) in PHP5 for one of my clients. PHP is not normally used for writing daemons; rather, it’s used as an in-process scripting language for Web pages. Zend, the creator of PHP, added a non-beta command-line interface (CLI) version of PHP in version 4.3.0, alongside a bunch of POSIX process-control functions and similar tweaks necessary to support most daemon-programming needs.

The last time I had to write a daemon of this sort was for Remote Lounge in NYC. Remote consists of lots of “cocktail consoles” that are each comprised of a custom-designed breadboard running a PIC microcontroller that controls the attached pan-tilt camera, joystick, gas-plasma readout, telephone, and television. Each cocktail console is connected via good old reliable serial cabling to an IP-to-serial converter from Moxa. The daemon runs on a plain old Dell Debian Linux server and essentially acts as the master control program for all of the cocktail consoles, reading from and writing to each one as necessary.

I wrote that particular daemon in Perl, and my advice to anyone attempting to do the same is “don’t.” Perl’s motto is “There’s more than one way to do it,” and while this is one of Perl’s strengths I also find it to be its primary weakness. Perl is a great language and has lots of uses and packages and modules and really weird people who can write an entire program in one line, but it suffers from a remarkable consistency in how the resulting code ends up looking like utter, incomprehensible crap. That and object orientation is sort of an afterthought to Perl5, and the current project required strong object orientation.

PHP5, on the other hand, was written with a strong focus on its object-oriented functionality. PHP’s syntax is also much more structured than Perl’s. It is of course possible to write crap in any language, but some make it easier than others. With all other things being equal, a PHP program is generally easier to read than a Perl program (let the flamewars begin…)

This new daemon runs on servers with multiple-modem cards in them, and it’s responsible for dialing those modems, sucking down data from the remote modems, parsing that data, and dumping it into a database. The daemon is also clustered and runs on multiple servers. It fork()s and waits for its children to die and all the yummy pcntl goodness that comes with being a daemon.

By and large I have to say I have just been really impressed with command-line PHP. It works, and it works well, and it is very easy to get things done with it. As I abstract out more and more of the code I will post the basic classes so that other people can make use of them, and hopefully improve on them.