TopicObserver.com

Trond Pettersen on Web Development and Topic Maps

Category: Web Development

PHP is not Java but Java is not a Singleton

In a reply to my twitter rant about PHP’s lack of method overloading a while ago, I was pointed to PHP Advent 2008 / PHP is not Java by Luke Welling. The post discusses how PHP code may turn unnecessary complex by applying Java-style design to PHP code. Well, it tries to.

The point of the article is valid: you should definitively make use of the language’s built-in features instead of inventing your own. It uses a very bad example, though, and that’s what this rant is all about. Now, I am very late to the party here, but still want to point out the misconception.

Welling wrote:

In case you are not familiar with it, the singleton pattern is a general solution to many situations where you want only one instance of a particular class. [...]

class Singleton
{
    private static $myObject;

    private function Singleton()
    {
        // Providing a constructor to eliminate default public one.
    }

    public static function getInstance()
    {
        if (! isset(Singleton::$myObject) )
        {
            Singleton::$myObject = new MyObject();
        }

        return Singleton::$myObject;
    }

    private function __clone()
    {
    }
}

True.

An experienced PHP developer is much more likely to implement the same pattern as follows:

global $myObject;

if (!isset($myObject)) {
    $myObject = new MyObject();
}

False.

An experienced PHP developer would know that the Singleton pattern could still be used because it makes sure you only create 1 instance of the MyObject class. In Luke Welling’s example, you would always have to remember to check if there was an existing instance of $myObject available, else you’d end up with more than 1 instance of the class. Even worse: what if $myObject was not set, but MyObject had already been instantiated somewhere in your code? $myOtherObject, for instance? You could end up with $stillAnotherObject. More than 1 database connection, etc.

Hence, the experienced PHP developer would make use of the Singleton pattern, and do this instead:

global $myObject;

if (!isset($myObject)) {
    $myObject = Singleton::getInstance();
}

Or just

$myObject = Singleton::getInstance();

He’d then rest assured that even if MyObject had already been instantiated, $myObject would now reference the single instance.

(And I am still annoyed by the lack of method overloading in PHP5.x — it’s just stupid!)

MySQL BLOB to File in 20+ Lines of PHP Code

One of the nice things about PHP is how extremely quick it is to hack together a script that will save your day.

Today, I needed to throw together a script for converting some images stored as BLOBs in an old MySQL database of mine, to JPEG files stored on the file system (obviously, I knew that my database only contained JPEGs). It was a one time job, and so I set out to create a quick and dirty script to get the job done.

The job only took me about 20 lines of code, due to PHP’s built-in MySQL support and file handling support. I’ve cleaned it up a bit before posting it here, though, so now it takes a whole lot of 27 lines due to the verboseness of the somewhat cleaned up code.

In cases like this, hard coding the DB credentials and directory paths wont make me loose sleep. Neither does doing it the procedural way. The script did it’s job, and I got what I wanted … without spending a single calorie too much.

<?php
$conn = mysql_connect('localhost', 'myuser', 'mypass');
mysql_select_db('mydb', $conn);

// returns rows of id, img_name and img_data
$sql = 'select * images';
$queryResult = mysql_query( $sql, $conn );

while( $row = mysql_fetch_object( $queryResult )) {
	processRow( $row );
}

mysql_close($conn);

function processRow( $row ) {
	$basedir = 'images/';
	$imagename = makeSafeImageName( $row->img_name );
	// in my case, file names are not unique, so I add the id
	$filename = $basedir . $imagename . '-' . $row->id . '.jpg';
	file_put_contents( $filename, $row->img_data );
	echo 'done dumping ' . $filename ."\n";
}

function makeSafeImageName( $source ) {
	return strtolower(preg_replace('/([^\w\d\-_]+)/', '-', $source));
}
?>

(Execute from command line with php my-script.php, or web server).

Readable Code: In the Eye of the Beholder?

In his most recent blog posting – In the Eye of the Beholder (ah, reminds me of EoB II), JavaScripter James Padolsey (if you do some JavaScripting / jQuery, follow his blog) argues that the readability of anything is entirely dependent on who’s doing the reading. He also states that readability depends on how proficient the reader is in the given programming language.

I tend to disagree. Readability and understanding are two separate concerns. Readability is about aesthetics. Understanding is about knowledge. Code can be understood without being classified as “readable”.
Read the full post »

What I Like About C#

Coming from the Open Source world I had never really worked with .NET – except for some minor Sharepoint 2007 stuff – until last September. That’s when I joined a project maintaining a .NET application written in C#.

Since I had previously worked with Java, becoming a (visiting) C# developer wasn’t that much of a leap. After all, C# was partly influenced by Java (learning new frameworks did of course impose some learning curve, but that’s of course independent of language).

C# has some nifty features that Java lacks, though. In many ways, it feels like a more modern language — pardon me for saying so! :D

What follows are some of the things that I’ve started to like about C#.
Read the full post »

Open to Web Development Opportunities in the US

Shoot me an e-mail at trondpet[curly-thingy]hotmail.com if you’re a US based employer in need of a sr. web developer with a proven track record. I’m a US citizen with no need of sponsorship.

My strengths are web development and -programming — from architecture and back-end programming to front-end coding. Below is a list of some of my skills. More about my project experience.

  • PHP4/5 (WAMP/LAMP)
  • Java
  • JSP
  • MySQL
  • MSSQL
  • XSLT
  • JavaScript / Ajax
  • jQuery
  • XHTML
  • CSS
  • Topic Maps
  • Information Modeling / Ontology Development
  • Cross-Browser Issues
  • WAI

I’ve currently got a few opportunities in sight, but am still open for exciting offers and am available for hire from early April on (arrive in the US on April 5 2010). I am primarily interested in opportunities on the West Coast — Greater L.A. Area, San Francisco Bay Area, Seattle and Portland, OR.

Feel free to contact me at trondpet[curly-thingy]hotmail.com, LinkedIn or Twitter.

Edit: I am no longer seeking new opportunities :)

Web Application Development with Ontopia – 3. Creating the JSPs

Happy New Year 2010

After a busy December month, the Christmas vacation finally gave me some room to concentrate on what really matters.

Here’s my third blog post on building web apps with Ontopia. A bit late – I had hoped to have it out before Christmas – but at least I made it within January 01 2010 … have a good one!

Getting to the Point

This blog post is part of a series on Web Application Development with Ontopia.

  1. Part 1: Installation & Requirements
  2. Part 2: Creating the Database
  3. Part 3: Creating the JSPs

In Part 2 of this series on building web applications with Ontopia we had a look at how to set up an application’s domain model using Ontopoly.

This post discusses how to go about building a custom web interface to present the data.
Read the full post »

Web Application Development with Ontopia – 2. Creating the Database

Intro

This blog post is part of a series on Web Application Development with Ontopia.

  1. Part 1: Installation & Requirements
  2. Part 2: Creating the Database
  3. Part 3: Creating the JSPs

In part 1, we looked at how to set up Ontopia. We also described the application that we intend to build (a blog) and what we need to develop in order to achieve our goal.

This time we’ll look at how to set up the “database schema” and create new blog posts by using Ontopia’s web interface. The resulting topic map can be browsed here.

Read the full post »

  • RSS @twitter

    • Also starting to like YUI3 vs. the framework I used to be more familiar with .. a.k.a jQuery :D
    • CI and "commit early and often - with unit tests" actually works great if done properly and throughout the team(s). Starting to enjoy it :-o
  • Tags

  • Topics

  • Recent Comments

  • Topic Map Feeds