Google’s Search Appliance

June 4th, 2008 by nick

Google MiniI recently had the opportunity to work with one of Google’s latest search applances, the Mini. Having no previous experience with any of Google’s search hardware, this seems an excellent opportunity to offer a newcomer’s first impressions.

I. Setup & Configuration

Setting things up turned out to be more painless than I had expected. Upon opening the box, I found the contents to be only what was necessary. It consisted of 5 things: the Mini itself, a yellow Cat5 cable, an orange Cat5 crossover cable, a power cable, and the manual/quick-start guide (and a snazzy tshirt!). That’s it, nothing else! No product catalogs, no coupons, no massive collection of multilingual warranty booklets, and most importantly no unnecessary clutter.

II. User Interface

The UI of the administration panel is clean and to the point - very much what one would expect from Google, and consistent with Google’s overall style across the rest of their product line. All the administrative functions are organized categorically and only one menu-level deep, making virtually any administrative action no more than 2 clicks away.

III. API/Programmatic Usability

Accessing the mini’s search capabilities programmatically works very much as one might expect - executing search queries via GET or POST and returning the results in an easily parsable XML format. Additional options are also available, though I found the XML format to be the most flexible for the circumstances. It is so easy to use I actually had to debate whether or not writing a PHP wrapper class was actually necessary. In the end I decided it would make sense, though even then writing the class itself was a breeze.

IV. Thoughts

Overall I am very impressed with this little beast. It clearly isn’t over-engineered and for its intended scale of use it is not underpowered. I would have liked to see more flexibility in managing the crawling process and in how results were returned, but these things would have been icing on a cake that is already fantastic on its own.

For anyone considering the acquisition of one of these, I highly recommend it. For small to medium applications you can’t beat the price, especially when compared to the mini’s bigger brother. And its usability both through the UI and programatically are very intuitive and easy to dive into. Well done Google, well done!

An API reference does a method’s body good…

March 31st, 2008 by nick

Got API?gotAPI.com is one of the most useful online resources I’ve come across, primarily because it places resources spread all over the internet into one simple site. I’ve been using this for quite some time, and have for the most part I have taken its usefulness for granted. Then it occurred to me that I might not be the only one that could find this tool useful (I know, it was a big ‘DUH!’ moment). So now I will share this gem with others…

gotAPI acts as a portal to almost any API/language reference available on the internet. Wondering what that PHP string function is that splits a string into an array? Pour yourself a nice tall glass of gotAPI and find it in seconds. Or if JavaScript is more your thing, browse the DOM to find the function or property you need. The advantage is that it can all be accessed from here, no need to remember countless URLs or stumble through a poorly designed site to find the documentation page. Simply hit up the site and you’re set.

Customization is another advantage, with the tabbed interface allowing you to pull up multiple reference pages (all searchable with an expandable tree view to your left). Load up all the API’s related to your current project finding an obscure function is now seconds away. Fantastic!

The fact that I am still excited about this site after months of using it should tell you just how nifty it is. So stop wasting time reading blogs and go check it out!

Link: gotAPI

Make PHP Growl

March 26th, 2008 by nick

GrowlI stumbled upon a fantastic PHP class today and felt compelled to comment on it. Originally written by Tyler Hall, this class allows you to send notifications to any system running Growl from a PHP script. For those of you that don’t know, Growl is an application written for Mac OS X that is intended to act as a universal notification tool (much like the taskbar notification bubbles we’ve all come to know and love in Windows XP/Vista).

The class itself is incredibly simple and straightforward, and allows you to send notifications using only 5 lines of code. Consider this simple example:

// Setup
$growl = new Growl();
$growl->setAddress('127.0.0.1');
$growl->addNotification("Test");
$growl->register();
 
// Send Notification
$growl->notify("Test", "Test Alert", "The body of the test alert!");

 
Pretty nifty isn’t it? One could very easily integrate this into a logger to notify you immediately of any critical errors with your scripts, or even tell you every time a given page is viewed. So if you want to check out my modified version (a bit more standards-compliant with PHP 5) you can see it here, or view the original author’s site to see the original.

Download: Growl PHP Class

PHP 5.3 - A Heavy Hitter in Training

March 12th, 2008 by nick

The evolution of PHP into an object-oriented programming language has been a very exciting process to watch. I’ll admit its advancement seems to move at a glacial pace at times, but looking back we certainly have come a long way. With the release of 5.0 we saw PHP leave its childhood and enter its awkward adolescent stage. At this point there is evidence of a mature and complex object-oriented language while stilll exhibiting many of its younger habits.

This release may be the most significant update PHP has seen since PHP 5. This is because many of the features planned for the first release of PHP 6 are being backported to 5.3. Anyone that has been folowing the development of PHP is likely aware that 6.0 will represent its entrance into what I like to call its adulthood. This milestone will mark the end of support for deprecated non compliant code, and will fully embrace an OO coding style. It’s not going to be the end-all be-all version of PHP, but it will no longer attempt to cling to its procedural roots.

Let’s take a look at some of the goodies in store for us in PHP 5.3:

I. Native MySQL Support

As of right now PHP has made use of the external library libmysql to access MySQL databases, which is fine - it works and it works well, so no complaints here. However, the relationship that has developed between PHP and MySQL is quite widespread, and I must admit it seems odd that MySQL has never truly been natively supported. All that will change in 5.3, when PHP will natively support MySQL resulting in a significant performance boost.

II. Variable Static Calls

You are probably already familiar with variable variables and variable function calls. Variable static calls are the next logical addition to this feature set. This concept is best illustrated with an example, so consider the following:

$className = 'StringUtils';
$functionName = 'FormatPhoneNumber';
 
$phoneNumber = '2535552552';
$newPhoneNumber = $className::$functionName($phoneNumber);
 
echo $newPhoneNumber;

 
If we assume that the function StringUtils::FormatPhoneNumber() formats the phone number into a friendly layout, we could expect the above script to output “(253) 555-2552″ or something similar. This adds a tremendous degree of flexibility to your code, as I’m sure you can already imagine.

III. Error Reporting

Error reporting has been expanded and has split E_STRICT into two separate reporting levels. E_STRICT now only reports on bad coding style and leaves deprecated code (code that will not be supported much longer) to the E_DEPRECATED level.

Additionally, E_ALL will actually include E_STRICT errors as well (which is what most of us expected to happen when it was first introduced).

IIV. Namespaces

I saved the best for last. Namespace support is hands-down the feature I am most excited about. This is some thing many developers with experience in other languages have been clamoring for since PHP first started supporting classes. Namespaces allow you to group related classes together and help to avoid naming conflicts in more complex applications.

Currently the only way to accomplish this is to simulate namespace funcionality by using very long class names. Consider the Zend Framework as an example, in which you end up with class names like “Zend_Auth_Adapter_Http_Resolver_File” or “Zend_Controller_Router_Route_Module” - just mildly inconvenient, isn’t it?

As of PHP 5.3 one could place these classes in namespaces, making them much more manageable:

namespace Zend::Auth::Adapter::Http::Resolver
 
class File {
    public function __construct() {
        // Do something here...
    }
 
    public function setFile($path) {
        // Do something else here...
    }
}

 
We could then instantiate the class like this:

use Zend::Auth::Adapter::Http::Resolver as HttpResolver;
 
$file = new HttpResolver::File();
$file->setFile('/home/testuser/file.tmp');

 
In the above case, we can now instantiate all classes within this namespace using a similar declaration. As you can see, the addition of namespaces allows you to declare the namespace in which a script will execute, greatly shortening the required class declaration. This also introduces the possiblity of namespace aliases, allowing you to reference a namespace with a shorter ‘nickname.’

We could have called the class directly from the namespace (like “new Zend::Auth::Adapter::Http::Resolver::File()”) and left out the use construct, but then we would be back to a long class declaration. Even then, this time around PHP will actually be aware of the namespace (and potentially future IDEs, leading to more powerful code-hinting).

Conclusion

That was just a sample of what you can expect when 5.3 is released. With so many additions that were originally planned for PHP 6, this release is going to feel like an early birthday present. This also means we can see these features added to our production environments more quickly considering an upgrade to 5.3 will go much more quickly than a migration to an entirely new verison.

PHP Patterns, Part III

January 29th, 2008 by nick

The Template Object (or TO) is a design pattern of my own that I developed to fill the role of the View layer in the MVC model. As you have probably figured out, the purpose of the TO is to handle everything related to the user interface. The idea here is to separate the interface as much as possible from the rest of the application, so that we could do a complete rewrite of an application without ever touching (or accidentally “breaking”) the view portion.

This object was designed around a template model, in which the HTML/CSS is stored completely independent of the template object. Using this approach, the appearance of the web application and how it operates are completely decoupled. Both the view layer and the rest of the application can be completely replaced without affecting each other.

So before I bore you to death with my talking, let’s take a look at some code. Below is some sample code for an abstract TemplateObject class, and then a basic FormTO class that would be useful for a basic web form:

/**
 * Abstract TemplateObject Class
 */
abstract class TemplateObject {
    abstract function render();
    abstract function setTemplate($template);
}
 
/**
 * Generic Form Template Object
 */
class FormTO extends TemplateObject {
    protected $template;
    protected $method;
    protected $action;
    protected $name;
 
    /**
     * Default Constructor
     * @param string $method the form method (post/get)
     * @param string $action the form action
     * @param string $name the name of the form
     * @param string $template the location of the template file
     */
    public function __construct($method = post, $action = ,
            $name = , $template = ) {
        $this->template = $template;
        $this->method = $method;
        $this->action = $action;
        $this->name = $name;
    }
 
    /**
     * Renders the page using the currentlyl stored values.
     */
    public function render() {
        try {
            include($this->template);
        }
        catch Exception($ex) {
            print(The specified template was invalid.);
        }
    }
 
    public function setTemplate($template) {
        $this->template = $template;
    }
 
    public function setMethod($method) {
        $this->method = $method;
    }
 
    protected function printMethod() {
        print($this->method);
    }
 
    public function getMethod() {
        return $this->method;
    }
 
    public function setAction($action) {
        $this->action = $action;
    }
 
    protected function printAction() {
        print($this->action);
    }
 
    public function getAction() {
        return $this->action;
    }
 
    public function setName($name) {
        $this->name = $name;
    }
 
    protected function printName() {
        print($this->name);
    }
 
    public function getName() {
        return $this->name;
    }
}

 
As you can see this is a fairly simple setup. We have a simple Template Object that we can use to set various values for the page it reperesents. It essentially acts as an interface to the actual web page. Now lets take a look at what a template file might look like. Remember, the added felxibility here is that the template file can do anything it wants with the data that has been stored in the TO. It has full control over how the information is presented. For illustrative purposes, I will make my example as simple as possible:

<form method="<?php $this->printMethod() ?>"
      action="<?php $this->printAction() ?>"
      name="<?php $this->printName() ?>">
    <!-- FORM CONTENT WOULD GO HERE -->
</form>

 
I’m sure you can imagine how easy it becomes to expand upon this simple design to build a very flexiple and complex web application in very little time. Using this approach, a developer could build a site without any concrete design in place, using a simple layout that could easily be replaced further down the road without rewriting or refactoring any code. This also allows designers to build an interface without having to understand the backend structure of the application. Pretty handy if you ask me!

Technical Debt

December 21st, 2007 by nick

The concept of technical debt (first coined by Ward Cunningham) has been something that has wandered about my head without a name for quite some time. The other day I read an article that finally put it into words. It is what I have always seen as the reason writing beautiful code is not just an endeavor in aesthetics. At this point you’re probably wondering what the heck I’m rambling on about. Don’t give up on me yet, I’m about to explain . . .

For most developers, time is a commodity that is often scarce and very expensive for our employers. With a resource in such high demand, it is no surprise that there is a temptation to do what we can to conserve it. Certainly there is nothing wrong with being efficient, but there is also a point at which efficiency ends and technical debt begins. Technical debt is created when we start to write sloppy code, “hacks,” or make other wreckless time-saving maneuvers. While we may save time in the immediate future, we are actually incurring a debt that will eventually have to be repaid, with interest.

The interest basically encompasses the extra time and effort we have to spend fixing bugs and making improvements as a result of the earlier shortcuts that were made. Just like financial debt, technical debt can be paid off. This is done through code rewrites and corrections to bring the quick-and-dirty code up to snuff. The longer we leave the debt unpaid, the more the interest grows until it ultimately can bring a development team to its knees.

Technical debt can actually be a useful tool, if handled responsibly. You can choose the quick-and-dirty route to save time and meet a deadline, and then later repay that debt by fixing the code afterwards. This way you can release planned functionality on-time and “save face” if you are developing software for a client or third party. Be weary of this practice though, while clients may only be concerned that something “works” they will also be the first ones to complain when something goes wrong and it takes you unusually long to fix it. Just like a credit card, this approach requires that you follow through with your obligation to repay your balance later.

So the next time you’re deep into a project and you think “I could throw something together in 5 minutes and everything will work” don’t forget that the 5 minutes you saved could cost you hours six months later when a client requests new features or bug fixes. Make sure it’s a debt you are able and willing to repay.

Find out where all your time is going…

November 28th, 2007 by nick

Having stumbled upon RescueTime, I feel compelled to share my discovery as this concept is just too useful to keep to myself. The basic idea behind this website is to make it easier to keep track of where you spend your time while at your computer. If you find yourself filling out your timesheet at the end of the week only to realize you can’t remember what you were doing all that time, this tool was made for you!

It requires a lightweight download (both Mac and Windows versions are available) that monitors what applications and web pages have focus and for how long. It then periodically sends this data to the RescueTime website where you can view an analysis of where all your time is spent.

You have a fairly large amount of control over how the stats are handled. You can attach multiple tags to each application, making it easy to categorize things and see how much time you spend in different areas. Below is an example of how much time I’ve spent this week on different things:

 

PHP Patterns, Part II

November 14th, 2007 by nick

In this installment, we will be looking at two patterns that have been ‘borrrowed’ from Java. If you’ve had any development experience with J2EE, you are probably well aware of how handy Data Access Objects and Value Objects can be. If you haven’t, don’t fret! This article was written especially for you!

If you’ve never heard these terms before, you may be wondering why I have chosen to group them together within one article. The simple explanation is … well you’ll see. For now just accept that they go hand-in-hand, much like salt and pepper or peanut butter and jelly or .

Excited? Let’s dig deeper…

I. Data Access Objects (DAOs) and Value Objects (VOs), an Introduction

These two classes comprise what is often called the “model” layer of the MVC (Model View Control) model. If you aren’t familiar with this concept do yourself a huge favor and read up on it - it will save you and your peers quite a bit of time further down the road on any project.

The DAO is basically the object you use to query your data source within your application. Rather than sprinkling SQL queries throughout your code, it allows you to encapsulate everything related to accessing your database within a single class. That way, if you ever change databases or need to tweak a query, you can do it in one place that’s easy to find. Think of it like a filing cabinet that keeps all your papers from floating all over your desk.

The VO does what you might expect a “value object” to do - it holds values. It provides you with a nifty object to pass around your application and typically contains a single row of information from your database. Again the goal here is to simplify the process of handling data retrieved from the database.

II. The VO, A Closer Look

Creating a VO is probably one of the simplest classes you will ever create. It basically mirrors a table in your database, with setter and getter methods for each field in that table. First, let’s pretend you have a simple database table called “users” that has the following columns:

  • id
  • user
  • pass

 
Using this information, we can create our very first Value Object:

class UserVO {
    protected $id;
    protected $user;
    protected $pass;
 
    public function setId($id) {
        $this->id = $id;
    }
 
    public function getId() {
        return $this->id;
    }
 
    public function setUser($user) {
        $this->user = $user;
    }
 
    public function getUser() {
        return $this->user;
    }
 
    public function setPass($pass) {
        $this->pass = $pass;
    }
 
    public function getPass() {
        return $this->pass;
    }
}

 
Pretty simple and to the point, huh? You may be wondering why I have gone through and written explicit setters and getters for each value, rather than just making two generic functions (or simply making the class variables public). The primary reason for this has more to do with coding standards than anything else. It is usually good practice to prevent class variables from being accessed directly. This way you don’t have to anticipate what might happen ouside the class. By declaring functions for each specific value, you have more control over the use of each value as well. For instance, where appropriate, you could use the addslashes() and stripslashes() functions to automatically massage data before it is inserted into the database.

II. The DAO, A Closer Look

Now that we have created our first VO, let’s take a look at its partner in crime, the DAO. Let’s take a look at some code before we start picking it apart:

class UserDAO {
    protected var $connect;
    protected var $db;
 
    // Attempts to initialize the database connection using the supplied info.
    public function UserDAO($host, $username, $password, $database) {
        $this->connect = mysql_connect($host, $username, $password);
        $this->db = mysql_select_db($database);
    }
 
    // Executes the specified query and returns an associative array of reseults.
    protected function execute($sql) {
        $res = mysql_query($sql, $this->connect) or die(mysql_error());
 
        if(mysql_num_rows($res) > 0) {
            for($i = 0; $i < mysql_num_rows($res); $i++) {
                $row = mysql_fetch_assoc($res);
                $userVO[$i] = new UserVO();
 
                $userVO[$i]->setId($row[id]);
                $userVO[$i]->setUsername($row[username]);
                $userVO[$i]->setPassword($row[password]);
            }
        }
        return $userVO;
    }
 
    // Retrieves the corresponding row for the specified user ID.
    public function getByUserId($userId) {
        $sql = "SELECT * FROM users WHERE id=".$userId;
        return $this->execute($sql);
    }
 
    // Retrieves all users currently in the database.
    public function getUsers() {
        $sql = "SELECT * FROM users";
        return $this->execute($sql);
    }
 
    //Saves the supplied user to the database.
    public function save($userVO) {
        $affectedRows = 0;
 
        if($userVO->getId() != "") {
            $currUserVO = $this->getByUserId($userVO->getId());
        }
 
        // If the query returned a row then update,
        // otherwise insert a new user.
        if(sizeof($currUserVO) > 0) {
            $sql = "UPDATE users SET ".
                "username='".$userVO->getUsername()."', ".
                "password='".$userVO->getPassword()."', ".
                "WHERE id=".$userVO->getId();
 
            mysql_query($sql, $this->connect) or die(mysql_error());
            $affectedRows = mysql_affected_rows();
        }
        else {
            $sql = "INSERT INTO users (username, password) VALUES('".
                $userVO->getUsername()."', ".
                $userVO->getPassword()."')".
 
            mysql_query($sql, $this->connect) or die(mysql_error());
            $affectedRows = mysql_affected_rows();
        }
 
        return $affectedRows;
    }
 
    // Deletes the supplied user from the database.
    public function delete($userVO) {
        $affectedRows = 0;
 
        // Check for a user ID.
        if($userVO->getId() != "") {
            $currUserVO = $this->getByUserId($userVO->getId());
        }
 
        // Otherwise delete a user.
        if(sizeof($currUserVO) > 0) {
            $sql = "DELETE FROM users WHERE id=".$userVO->getId();
 
            mysql_query($sql, $this->connect) or die(mysql_error());
            $affectedRows = mysql_affected_rows();
 
        return $affectedRows;
    }
}

 
The Data Access Object consists a handful of basic methods. First is the constructor, which basically initiates the connection to the database. You pass it the database connection info and credentials, and it takes care of the rest.

Next comes the getter functions, which basically represent a collection of the queries used to access the database. For example, you might have a getByUserId() method that returns the UserVO we created above filled with the corresponding data for a particular user ID.

Following the getters is the save() function, which essentially does what you would imagine it does. You pass a VO to it and it will either update an existing record if it finds one that matches the VO or will insert a new row. I’ll bet you’re thinking what I thought the first time I learned of this function: “holy cow! that just reduced 8+ lines of code down to one!”

Finally we have the big scary delete() function that, you guessed it, deletes a record from the database. To make it slightly less scary, it requires that you pass it a VO that matches a database row exactly. This will force you to have first retrieved the row you want to delete before calling this method. This helps prevent the accidental deletion of a record.

And there you have it! Together these two classes can save you a tremendous amount of effort and time, makes it much easier to maintain say 6-12 months from now when you have completely forgotten how you wrote that file manager script.

A side note: If you live in fear of having to write these classes for databases with 100 tables that have 200 columns each, don’t despair! With the help of Google you can find countless PHP DAO and VO generators that will build the code for you (take a look here for example). Some will do it based on existing database tables, and others will do it based on what you tell them. They might still require some tweaking afterwards, but at least that way the hard part would be done and over with.

A GUI Mess, or a Productivity Booster?

October 3rd, 2007 by nick

While writing up a review on a database tool I discovered today, I was inspired to spark a discussion about database GUIs in general. The value of GUI tools for administering database systems like MySQL has been a topic of much debate.

The purist/traditional camp argues that a GUI imposes limitations on the user when working with the database. They will claim that it presents the user with a subset of the available features for a given database. They also suggest that the addition of another layer (a “presentation layer” perhaps?) increases security risks and can degrade performance.

In the other camp we have supporters that argue a GUI can increase productivity tremendously. Repetitive tasks can be automated, complex commands can be assembled in seconds rather than minutes, and for new users the learning curve can become quite a bit more forgiving.

I tend to lean towards the pro-GUI group, as it is hard to deny the productivity gains when using an admin tool that is well designed. However, I must acknowledge the importance of having command line experience. There are a number of reasons for this. For one, there will always be those complex queries and processes that a GUI designer will not have anticipated that you will have to crunch out manually. Perhaps more importantly, you will have a greater understanding of the inner-workings of whatever database you are working with. This knowledge can be essential when it comes to debugging and performing complex admin tasks (even from within a GUI).

The nutshell version: I think GUIs are great, but use them and don’t abuse them. Make sure you know how to perform a task without an admin GUI before you use one. It may not be fun or easy, but it will definitely pay off in the end.

So now I pose the question to you - on which side of the line do you stand? Are thare any pluses/minuses to each side that haven’t been mentioned yet?

PHP Patterns, Part I

September 16th, 2007 by nick

I. The Registry Pattern, an Introduction
I am going to kick off this series by introducing you to the registry pattern. First, imagine you are deep into a complex web application and you come to the realization that you have several objects that all require access to your database. Your first inclination may be to simply have each class initiate their own connection to the database and use it as they please. But then you’ll start to hear that little voice in the back of your head, screaming something about how you’re needlessly wasting valuable system resources and bandwidth. Naturally you ask what else you could do - this is where a registry comes in handy.

A registry object basically acts as a container for objects that you want to be universally accessible throughout your project, while avoiding the use of . . . gulp . . . global variables! You’ll find that its implementation is fairly simple, but extremely powerful and convenient.

II. Class Definition
Let’s take a look at what a registry class is made of:

class Registry {
	protected $_objects = array();
 
	function set($name, &amp;$object) {
		$this-&gt;objects[$name] =&amp; $object;
	}
 
	function &amp;get($name) {
		return $this-&gt;objects[$name];
	}
}

Look at that! Pretty short and sweet eh? Now let’s rip it apart and see what each component does:

  1. Following the class definition, we have a protected class variable called $_objects which is an array that holds all the objects that are added to the registry.
  2. Next we find our first function called set which is inherently public. This function is used to add an object instance to the registry. You pass it the object instance, and pick a friendly name to remember it by (don’t forget it, you’ll need it later!).
  3. Finally we have our second and final function get which retrieves an object previously added to the registry. Simply supply the friendly name you picked earlier and it will return the instance to you.You may be wondering what that ampersand (&) is doing up in front of the function name. This tells the function to return the object by reference rather than making a copy of it and returning the copy (which would make all this work pointless, since we again would be wasting resources). This means that any changes or actions performed on the object will be reflected everywhere else it is used in your application.

III. Less Talk, More Action!
Now that we have the basic concept outlined, let’s take a look at how we might use our new creation. Let’s say we have a simple class that returns a user’s name, and another class that checks if a given user has “admin” status. In practice you would probably group this functionality into a single class, but for the sake of illustration we will pretend Captain Obvious is on vacation:

// First we create our database and registry objects
$db = new databaseConnection();
$registry = new registry();
 
// Then we add the db object to the registry
// It will now be available anywhere the registry is also available!
$registry-&gt;add($db, "database");
 
// Now we create the objet that gets our username and checks for admin status
$user = new username($registry);
$admin = new admin($registry);
 
$username = $user-&gt;getUser(12);
$isAdmin = $admin-&gt;check($username);
 
// Finally, we display the user's info
echo("Username: ".$username."");
echo("Is Admin? ".$isAdmin);

Now, you’ll have to use your imagination to see how the two objects are able to use the same database instance, but let’s take a peek into what they both do:

----- snip -----
 
//First they get the database object from the registry
$databaseObj = $registry->get("database");
 
//Then they use it as they see fit
$databaseObj->query("SELECT username FROM users WHERE id=$userId");
 
----- snip -----

Congratulations, you have just learned how to create and use a registry! Now go forth and use what you have learned to write more efficient code!

Next Entries »