Archive for the 'Tutorials' Category


PHP: Double quotes vs Single quotes

Monday, August 20th, 2007

If you don’t know the difference between using double quotes or single quotes when using Strings in PHP, you should. The PHP Manual page for Strings covers all this, but basically strings created with double quotes will be parsed by PHP. This example shows what I mean:

Code:
// they both output 'Yahoo Google'
$str = 'Google';
echo 'Yahoo' . $str;
echo "Yahoo $str";

At first glance you might think, who cares? The key note is deep in the manual page:

Parsing variables within strings uses more memory than string concatenation. When writing a PHP script in which memory usage is a concern, consider using the concatenation operator (.) rather than variable parsing.

PHP: Sorting an array of objects by a method/member

Sunday, August 19th, 2007

Earlier today I was looking to sort an array of object by a given datetime member. After a couple quick tests I realized that PHP was capable of comparing MySQL DATETIME strings natively. I guess that makes sense, since all they really have to do is convert the string to a timestamp via strtotime. In any case, after a bit of searching I found a method similar to the one below in a comment posted on the PHP Sort manual page. I changed the method a bit to compare using a public class method, sort in descending order and return a new array. I hard coded the function name cause from what I know you can’t pass in the function name as a parameter (you can if it was a key).

Code:
function sortObject($data) {
	for ($i = count($data) - 1; $i >= 0; $i--) {
		$swapped = false;
		for ($j = 0; $j < $i; $j++) {
			if ( $data[$j]->getTime() < $data[$j + 1]->getTime() ) {
				$tmp = $data[$j];
                $data[$j] = $data[$j + 1];
                $data[$j + 1] = $tmp;
                $swapped = true;
			}
		}
		if (!$swapped) {
			return $data;
		}
	}
}

Here is an example of the above function sorting four datetime strings:

Code:
class DObject {

	private $dt;

	public function __construct($d) {
         $this->dt = $d;
    }

	public function getTime() {
		return $this->dt;
	}

}

$date1 = '2009-08-05 03:24:57';
$date2 = '2006-08-05 23:44:56';
$date3 = '2007-08-05 20:14:56';
$date4 = '2005-02-10 12:24:06';

$toSort = array();

array_push($toSort, new DObject($date1));
array_push($toSort, new DObject($date2));
array_push($toSort, new DObject($date3));
array_push($toSort, new DObject($date4));

echo "<pre>";
print_r($toSort);
$result = sortObject($toSort);
print_r($result);
echo "</pre>";

Object-Oriented Features in PHP 5

Thursday, August 2nd, 2007

I came across a good writeup on linuxjournal.com talking about the OO features/capabilities in PHP 5. I guess the most important thing to note is that objects (i.e. objects of classes, not arrays) are now passed by reference. The writeup, which was taken from the book Object-Oriented PHP by Peter Lavin, explains their rational for doing this and how the entire scripting engine underlining PHP had to be re-written. All other types of variables are still passed by value (including arrays), but you can easily pass them by reference by adding an & to the function definition.

Code:
$tempArr = array();
$tempArr[0] = 1982;
$tempArr[1] = 2007;

echo "originally:";
printArray($tempArr);
tempFunc2($tempArr);
echo "after chang in function";
printArray($tempArr);

function tempFunc2(&$obj) {

	$obj[0] = 1;
	$obj[1] = 2;
}

function printArray($ta) {
	echo "<pre>";
	print_r($ta);
	echo "</pre>";

}

CSS Design Patterns

Wednesday, April 25th, 2007

The other night I spent some time thinking about patterns and CSS. I wanted to find some intuitive way of developing/creating the styles for widgets, fonts, lists, etc.. without just mashing together styles were ever they fit. I came across an interesting discussion about the concept here. The one idea that stood out was the “Inheritance” pattern:

..CSS doesn’t have inheritance in the way that OOP languages do, but you can use something close to it using MultipleClasses. Here’s an example:

Code:
<style>
.baseClass { color: #fff; background: #009; margin: 10px; padding: 10px; }
.childClass1 { color: #f99; }
.childClass2 { text-transform: uppercase; }
</style>

<div class="baseClass">Some content here</div>
<div class="baseClass childClass1">Some content here</div>
<div class="baseClass childClass2">Some content here</div>

By applying both a base class and a child class (or classes) you get the properties of both, with the child overriding the base, much like in OOP inheritance. This is a design pattern rather than a specific technique because it can be applied to all kinds of situations..

Tech Talk: Dojo JavaScript Toolkit slides

Thursday, March 1st, 2007

I’m giving a tech talk today at work on a JavaScript Toolkit called Dojo. I made the slides based off of the dojo.book documentation. I uploaded the slides to Zoho, you can see them below. Hit the button in the bottom corner to maximize the presentation.

YUI: Blog, Library, Patterns, Theater

Tuesday, February 27th, 2007

I’m blown away at how “right” Yahoo is doing it. All too often I see corporation doing Open Source, but releasing some early, un-commented, buggy piece of crap to the public, while keeping the corporate version under wraps. Yahoo released their next version of the YUI Library the other day, this says it all:

YUI was released internally at Yahoo! about six months before it was released for public use under a BSD license in February 2006. Although the internal and external versions of the library were identical, the way we built and distributed them was different and we managed those differences with separate versioning tracks. Today we’re merging the internal and external project versioning and reaffirming that the YUI you can download here is exactly the same YUI Library used all across Yahoo!. Hence, we’re retiring the old public version series (which had reached 0.12.2) and we’re unifying the versioning of this release at v2.2.0.

Aside from the YUI Library and Patterns, theirs great video tutorials from industry folks (YUI Theater), including a total of 10 videos by Douglas Crockford covering all aspects of JavaScript.

YUI Blog
YUI Library
YUI Design Patterns
YUI Theater

How To: Making a PHP REST client to call REST resources

Friday, October 20th, 2006

A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.

An example would be Yahoo!’s Geocoding API, with the following URL:

Code:
http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&street=701+First+Street&city=Sunnyvale&state=CA

I would get:

Code:
<Result precision="address">
   <Latitude>37.416384</Latitude>
   <Longitude>-122.024853</Longitude>
   <Address>701 FIRST AVE</Address>
   <City>SUNNYVALE</City>
   <State>CA</State>
   <Zip>94089-1019</Zip>
   <Country>US</Country>
</Result>

So Yahoo! exposes the Geocode URL and allows you to query this resource using URL parameters like appid and street. Dynamically building your URL to query a given resource is OK, generally that’s what people do, like the following:

Code:
$base = 'http://xml.amazon.com/onca/xml3';
$query_string = "";

$params = array( 'ManufacturerSearch' => "O'Reilly",
    'mode'  => 'books',
    'sort'  => '+salesrank',
    'page'  => 1,
    'type'  => 'lite',
    'f'     => 'xml',
    't'     => 'trachtenberg-20' ,
    'dev-t' => 'XXXXXXXXXXXXXX' ,
);

foreach ($params as $key => $value) {
    $query_string .= "$key=" . urlencode($value) . "&";
}

$url = "$base?$query_string";
$output = file_get_contents($url);

The problem here, is that REST is meant to take advantage of HTTP methods GET, POST, PUT, DELETE, etc.. When people are showing examples which dynamically build queries and call file_get_contents, the average user doesn’t appreciate (understand) what type of request is being made. Do they care? Should they care? We’ll that’s another story. Eventually though, more intense REST resources will become widely available, and it will be critical the user (developer) understands if their making a POST or PUT request.

I came across a great PEAR package the other day called HTTP_REQUEST, which among many things supports GET/POST/HEAD/TRACE/PUT/DELETE, basic authentication, proxy, proxy authentication, SSL, file uploads and more. Using this package, I got started on a simple wrapper class called RESTclient, which gives intuitive support for making REST resource calls.

So if I was going to use RESTclient to call the Geocode API above, it would look like this:

Code:
<?php

require_once "RESTclient.php";

$rest = new RESTclient();

$inputs = array();
$inputs["appid"] = "YahooDemo";
$inputs["street"] = "701 First Street";
$inputs["city"] = "Sunnyvale";
$inputs["state"] = "CA";

$url = "http://api.local.yahoo.com/MapsService/V1/geocode/"
$rest->createRequest("$url","POST",$inputs);
$rest->sendRequest();
$output = $rest->getResponse();
echo $output;

?>

At this point, you might be thinking, who cares — what’s the difference between using a loop to dynamically generate the URL or RESTclient. There are lots of reasons, first off, I can easily call the Geocode resource again using another address just by changing:

Code:
$inputs["street"] = "1600 Amphitheatre Parkway";
$inputs["city"] = "Mountain View";

There was no need to re-generate the URL. Furthermore, I’m explicitly specifying a POST request. Just as easily I can make a PUT, DELETE, etc. request on a given resource by changing the createRequest method parameters.

The class below is RESTclient. Note, I put this together to prove a point, it still needs some work if you plan on using it.

Code:
<?php

require_once "HTTP/Request.php";

class RESTClient {

    private $root_url = "";
    private $curr_url = "";
    private $user_name = "";
    private $password = "";
    private $response = "";
    private $responseBody = "";
    private $req = null;

    public function __construct($root_url = "", $user_name = "", $password = "") {
        $this->root_url = $this->curr_url = $root_url;
        $this->user_name = $user_name;
        $this->password = $password;
        if ($root_url != "") {
            $this->createRequest("GET");
            $this->sendRequest();
        }
        return true;
    }

    public function createRequest($url, $method, $arr = null) {
        $this->curr_url = $url;
        $this->req =& new HTTP_Request($url);
        if ($this->user_name != "" && $this->password != "") {
           $this->req->setBasicAuth($this->user_name, $this->password);
        }        

        switch($method) {
            case "GET":
                $this->req->setMethod(HTTP_REQUEST_METHOD_GET);
                break;
            case "POST":
                $this->req->setMethod(HTTP_REQUEST_METHOD_POST);
                $this->addPostData($arr);
                break;
            case "PUT":
                $this->req->setMethod(HTTP_REQUEST_METHOD_PUT);
                // to-do
                break;
            case "DELETE":
                $this->req->setMethod(HTTP_REQUEST_METHOD_DELETE);
                // to-do
                break;
        }
    }

    private function addPostData($arr) {
        if ($arr != null) {
            foreach ($arr as $key => $value) {
                $this->req->addPostData($key, $value);
            }
        }
    }

    public function sendRequest() {
        $this->response = $this->req->sendRequest();

        if (PEAR::isError($this->response)) {
            echo $this->response->getMessage();
            die();
        } else {
            $this->responseBody = $this->req->getResponseBody();
        }
    }

    public function getResponse() {
        return $this->responseBody;
    }

}
?>

How to: Building dynamic PHP objects and URL decoding example

Friday, October 6th, 2006

PHP is a powerful programming language; with every release I’m amazed with the new power and functionality. The ability to build dynamic objects (the way I’ll describe) I believe was introduced as of PHP 5. In any case, this is good stuff. There are lots of reasons why you would want to create a dynamic object, in my example below; you’ll see how to create a dynamic object of the URL query parameters.

At the heart of building dynamic PHP objects are the PHP Magic Methods. From the PHP manual:

The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __set_state, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Magic methods get called automatically through the parser when certain events occur. For example, just before you transition pages all objects you’ve created will call their respective __sleep methods. Most likely you wouldn’t have this method defined, so nothing would happen.

So now lets look at what happens when a certain method (or variable) of a given PHP object is called. Take the following code as an example:

Code:
$x = new obj();
$x->method1();
$x->var1;

When a method of a given object is called (like method1) the first thing the parser does is look for the associated name in the instance of the object. If the method is found, then the parser gives control to the method. If the method is not found, then the __call function is called with the function name and input values as a parameter. If this function returns true, then the object will return successfully. If a __call function does not exist, the parser will check the parent class (if exists) and so forth.

Similarly, if a variable of an object is requested (like var1) the parser looks in the object for a variable with that name. If a variable does not exist, the __get method is called with the name of the variable as a parameter, and so forth.

You should be able to see how we can now simulate (fake) the existence of methods and variables by using these magic methods. The code below shows the parent class G_Dynamic. This class would be the parent to specific subclasses that would require dynamic method/variable access.

Code:
<?php

/*  */

/**
 *
 * PHP versions 5.1.4
 *
 * George A. Papayiannis
 *
 * This class provides the magic functions needed to create
 * a dynamic object.  Subclasses would extend this object
 * and call the constructor with a parsed array.  See
 * g_url_decode.class.php for an example of creating a
 * dynamic object from the URL query string.
 *
 */

/**
 * Class definition
 */

class G_Dynamic {

    private $param = array();

    public function __construct($init) {
        $this->param = $init;
    }

    private function __get($name) {
        if (isset($this->param[$name])) {
            $res = $this->param[$name];
        } else {
            $res = false;
        }
        return $res;
    }

    private function __set($name, $val) {
        if (isset($this->param[$name])) {
            $this->param[$name] = $val;
            $res = true;
        } else {
            $res = false;
        }
        return $res;
    }

    private function __isset($name) {
        return isset($this->param[$name]);
    }

    private function __unset($name) {
        unset($this->param[$name]);
    }

    private function __call($name, $var) {
        // add code to simulate function call
        // return TRUE for success
    }

}

?>

As an example, I created a subclass to G_Dynamic called G_URL_Decode. This class takes the URL query string as input, parses it into an array and calls the parents (G_Dynamic) constructor. The code for G_URL_Decode is below:

Code:
<?php

/*  */

/**
 *
 * PHP versions 5.1.4
 *
 * George A. Papayiannis
 *
 * This class extends the G_Dynamic class to create a
 * dynamic object of the URL query string.  In another
 * file, you would have:
 *
 * require_once "g_url_decode.class.php";
 * $x = new G_URL_Decode($_SERVER['QUERY_STRING']);
 *
 * then you could have $x->(url param name) to access
 *
 */

require_once "g_dynamic.class.php";

/**
 * Class definition
 */

class G_URL_Decode extends G_Dynamic {

    private $queryParam = array();

    public function __construct($qs) {
         parent::__construct($this->parseURL($qs));
    }

    public function getQueryParam() {
        return $this->queryParam;
    }

    private function parseURL($qs) {
        $this->queryParam = array();
        $qs_parsed = explode("&", $qs);
		foreach ($qs_parsed as $value) {
			$paramVal = explode("=",$value);
			if (array_key_exists(1,$paramVal)) {
				$this->queryParam[htmlspecialchars(urldecode($paramVal[0]))] = htmlspecialchars(urldecode($paramVal[1]));
			}
		}
		return $this->queryParam;
    }
}

?>

Once the URL query string is successfully parsed, you can access the parameter names through the object. The code to bring it all together is below.

Code:
<?php

require_once "g_url_decode.class.php";
$x = new G_URL_Decode($_SERVER['QUERY_STRING']);
echo $x->var1;

?>

Using this as a base, you should be able to build some pretty cool dynamic objects.
Click here to download the source.

How to: PHP on the i5 – The i5 PHP API Toolkit and Calling RPG/CL Programs

Monday, September 25th, 2006

Before I begin to talk about PHP on the i5, a little history is in order. PHP was created by Rasmus Lerdorf in 1994 to replace a personal set of Perl scripts he used to maintain his website. He officially released version 1.0 in 1995 as a set of CGI binaries written in C, under the GNU General Public License. In 1997 two developers at the Israel Institute of Technology, Zeev Suraski and Andi Gutmans, re-wrote the parser releasing PHP 3.0 in June 1998. Zeev and Andi went on to create Zend Technologies, a company focused on pushing PHP for mission critical business applications. Rasmus currently works for Yahoo! and is actively involved in the development of PHP.

PHP and RPG have one thing very much in common, when they first came about they were meant to do pretty simple tasks and their names reflected that, Personal Home Page and Report Program Generator. As the years went on, both languages evolved, with RPG and PHP gaining various built-in functions (BIFs), new programming constructs, XML support, and more.

Zend provides two main components to the i5, the Zend Core and the Zend Platform. The Zend Core provides, among many things, the essentials needed to run PHP on the i5. This includes the PHP runtime, the i5 PHP Toolkit, native DB2 support, automatic security updates, a web-based administration console, and more. The Zend Platform provides addition features to the Core, including run-time code optimization, dynamic content caching, PHP/Java integration, and more.

In this article I will begin by giving an overview of the Zend Core installation. Next I will explain what the i5 PHP API Toolkit is and conclude by going through an example of calling an RPG program through PHP.

Installation

The Zend Core makes the installation of PHP on the i5 painless. To start off, create a SAVF in QGPL under the name ZCOREPROD. Then download the Zend Core for the i5/OS to your computer and transfer (via FTP) the included SAVF to your i5. There are numerous open source FTP applications available online, FileZilla is one example. Remember to do a binary FTP upload. Once uploaded, perform a RSTLICPGM command to start the installation, i.e.:

Code:
RSTLICPGM LICPGM(1ZCORE5) DEV(*SAVF) SAVF(QGPL/ZCOREPROD)  

Once the installation completes, you can test everything went OK by pointing your browser to: http://:8000/ZendCore/. This should take you to the web-based administration console for the Zend Core. More information on the installation can be found in the Zend Core for the i5/OS manual and i5php.net. You should now be able to put your scripts in /www/zendcore/htdocs/ and access the files through http://:8000/.

Zend also provides the Zend Studio for the i5/OS, a Java based IDE to assist in the development of PHP applications. IBM and Zend are currently working on the Eclipse PHP IDE project, with version 1.0 set to be released December 2006. For the purposes of this article, I’ll be using WDSC to work with the i5.

i5 PHP API Toolkit

The i5 PHP API Toolkit (iPAT) is an extension built into the Zend Core, giving PHP developers easy access to their i5, natively though PHP. The toolkit is broken apart into seven parts; these include Connection Management, CL Commands, Program Calls, Data Retrieval, Native File Access, System Values and Data Areas. All functions in iPAT begin with ‘i5_’ to ensure no namespace problems come about. The figure below shows the iPAT organizational layout, along with the associated functions.

i5 PHP API Toolkit

Calling RPG/CL program from PHP

The lifecycle of a PHP script calling an RPG/CL program has four main steps, these are connect, prepare, execute and close. A connection first needs to be made to the i5, this is done by using the i5_connect function, and passing in as parameters the i5 IP address, a username and password. The PHP code below shows this:

Code:
$conn = i5_connect("localhost", "gpapayia", "secret");

if (!$conn) {
    throw_error("i5_connect");
    exit();
}

If the connection returns false, then we know something went wrong. I created a function called throw_error, which takes as input a function name and outputs the error number and associated message from the last executed command. The PHP code below shows this function:

Code:
function throw_error($func) {
	echo "Error in function: ".$func." --- ";
	echo "Error Number: ".i5_errno()." --- ";
	echo "Error Message: ".i5_errormsg()."<br>";
}

Next, the program in question needs to be loaded into memory and prepared to be run. This is done by executing the i5_program_prepare function and passing in as parameters the name of the i5 program and a description of the inputs expected by the RPG code. Before I continue to explain this, I’ll introduce the RPG program I plan on using. For the purposes of this article, the example code I made is simple and serves only as illustration as to what can be done. The program takes as input a product id, a store location, and a price. The program updates the price by adding 10.99 and finishes. The RPG code below shows the stored procedure:

Code:
     C     *ENTRY        PLIST
     C                   PARM                    prod_id           7
     C                   PARM                    store_loc        10
     C                   PARM                    price             5 2
      /FREE
       price = price + 10.99;
       *INLR = *ON;
      /END-FRE

Now back to the PHP coding, once the connection is made to the i5, we need to load the given RPG program into memory and get it ready to be executed. This is done by using the i5_program_prepare function, and passing in as parameters the name of the RPG program and a description of the inputs expected. Describing the input variables may seem complicated at first glance, but it’s really is quite intuitive and straight forward. Each input variable is enclosed in an associative array by specifying the Name of the input, the IO being performed, the variable Type being passed in, and finally the Length. The PHP code below shows how this would be done. Notice how the third input, PRICE, has an IO field of I5_INOUT, since I plan on modifying this value from within the RPG code. There is no real difference between calling an RPG or CL program, just specify the correct program name in i5_program_prepare function and everything else stays the same. Again, after i5_program_prepare is executed, I check to make sure no error occurred.

Code:
$description = array(
    array(
    	"Name"=>"PROD_ID",
    	"IO"=>I5_IN,
    	"Type"=>I5_TYPE_CHAR,
    	"Length"=>"7"
    ),
    array(
    	"Name"=>"STORE_LOC",
    	"IO"=>I5_IN,
    	"Type"=>I5_TYPE_CHAR,
    	"Length"=>"10"
    ),
    array(
    	"Name"=>"PRICE",
    	"IO"=>I5_INOUT,
    	"Type"=>I5_TYPE_PACKED,
    	"Length"=>"5.2"
    ),
);

$pgm = i5_program_prepare("QGPL/GEOPGRM", $description);

if (!$pgm) {
    throw_error("i5_program_prepare");
    exit();
}

Notice the return value from the i5_program_prepare function is stored in the variable $pgm. From this point on, any time I want to refer to my RPG program GEOPGRM, I’ll use the variable $pgm. At this moment, the program is loaded into memory and is ready to be run. To execute the program, all I have to do is call the i5_program_call function and pass as parameters the prepared program ($pgm), my input parameters and where I want the output parameters to be stored. The PHP code below shows how this would be done. As above, the input and output parameters are stored in associative arrays. Notice in the $paramOut array, I specified for each given input to the RPG program, the variable names I want to refer to after the i5_program_call completes. For PRICE, I coded in AMOUNT, so after I execute my RPG program, I can get at the PRICE result by using a local PHP variable $AMOUNT. After I execute the RPG program, I check to see if an error occurred, assuming everything went OK, I output the input/output variables from my RPG program using the PHP echo function.

Code:
$parameter = array(
    "PROD_ID"=>"xyz101",
    "STORE_LOC"=>"a1001",
    "PRICE"=>0.00
);

$parmOut = array(
    "PROD_ID"=>"PROD_ID",
    "STORE_LOC"=>"STORE_LOC",
    "PRICE"=>"AMOUNT",
);

$ret = i5_program_call($pgm, $parameter, $parmOut);

if (!$ret) {
    throw_error("i5_program_call");
    exit();
}

echo "Product Id: ".$PROD_ID."<br>";
echo "Store Location: ".$STORE_LOC."<br>";
echo "Price: ".$AMOUNT."<br>";

At this point, my program executed correctly and I am ready to close my program (unload from memory) and close my connection to the i5. This is handled through the functions i5_program_close, taking as a parameter the prepared program, and i5_close, taking as a parameter the connection. The two lines of PHP code to handle this are listed below.

Code:
i5_program_close($pgm);
i5_close($conn);

One reason why PHP has become so popular is that it makes seemingly difficult tasks easy, this in turn frees the programmer to be innovative and spend more time thinking through ideas, rather than coding. Furthermore, resources to assist PHP developers are available all over the internet, including one of the best manuals for any programming language at php.net.

PHP Source Listing
RPG Source Listing

Dojo: A glimpse into the future of web development

Thursday, August 3rd, 2006

Update (Aug. 17 2006): The more I use Dojo, the more impressed I am with what is being done. The entire project has so much attention to detail. I just spent a little while looking at dojo.io.* and am blown away at this easy to use, transparent approach to AJAX.

That’s a powerful title, will it come true? Who knows. At this moment and time, at version 0.3, Dojo is insanely impressive.
So the first question that most people will have is: What is Dojo?

Dojo is the Open Source Javascript toolkit that makes professional web development better, easier, and faster

A little more detail:

Dojo is an Open Source DHTML toolkit written in JavaScript. It builds on several contributed code bases (nWidgets, Burstlib, f(m)), which is why we refer to it sometimes as a “unified” toolkit. Dojo aims to solve some long-standing historical problems with DHTML which prevented mass adoption of dynamic web application development.

Dojo allows you to easily build dynamic capabilities into web pages and any other environment that supports JavaScript sanely. You can use the components that Dojo provides to make your web sites more useable, responsive, and functional. With Dojo you can build degradeable user interfaces more easily, prototype interactive widgets quickly, and animate transitions. You can use the lower-level APIs and compatibility layers from Dojo to write portable JavaScript and simplify complex scripts. Dojo’s event system, I/O APIs, and generic language enhancement form the basis of a powerful programming environment

I hear people say “Dojo, that’s the AJAX framework”. Sure, Dojo is about asynchronous interaction, but that’s only a part of the story. The problem with JavaScript is that it blew up way too fast. It’s a powerful programming language, but lacks the subtleties, which would make it easy to develop large-scale JavaScript applications. I doubt in the mid 90s Netscape envisioned JavaScript the way its used today. In 2002, Doug Crockford got fed up and made JSLint:

When C was a young programming language, there were several common programming errors that were not caught by the primitive compilers, so an accessory program called lint was developed which would scan a source file, looking for problems. As the language matured, the definition of the language was strengthened to eliminate some insecurities, and compilers got better at issuing warnings. lint is no longer needed.

JavaScript is a young language. It was originally intended to do small tasks in webpages, tasks for which Java was too heavy and clumsy. But JavaScript is a very capable language, and it is now being used in larger projects. Many of the features that were intended to make the language easy to use are troublesome for larger projects. A lint for JavaScript is needed: JSLint, a JavaScript syntax checker and validator.

The good folks at Dojo have taken this a massive step further, put very gently:

dojo.lang.* contains wrappers for common idioms. It doesn’t provide replacements for language constructs. We only provide functions that provide value-added above the standard javascript routines, or functions that mask browser incompatibilites, etc.

The reality is, an amazing, transparent, useful framework has been (is being) developed, which will give the Web developer power they’ve only dreamt of. Were talking proper class constructs, inheritance, the ability to override methods, and much more.

In total there is the Dojo Infrastructure (fundamental behaviors), General purpose libraries (String manip., DOM manip., etc…), Data Structures (Dictionary, ArrayList, Queue, etc..), Web I/O (RPC, JSON, etc.), Visual Web (animations, graphics, etc.), Math and Cryptogrpahy (speaks for itself.. clientside Crypto, like Meebo) and a great Widget library.

What kind of widgets are we looking at? Here is a taste of what you can expect:

FisheyeList – hover over the menu at the top…
Popup Dialogs – click the links on the top left…
Floating Pane – drag them, close them.. the world is your oyster
Inline Edit Box – just like Flikr, click the title and text…

All this, and their only in version 0.3. Give it a try: dojotoolkit.com — be warned documentation to the specifics of the API is sparse.

How To: Bridging the Gap – Integrating PHP and Java

Thursday, July 20th, 2006

I set out a couple days ago, to see how I could use an existing Java class or Jar within a PHP application. From what I found there are essentially two ways of going about this. The first is to integrate Java support directly into PHP using a regular HTTP server, while the second was to deploy a custom made WAR file into a J2EE container like Tomcat.

One thing for sure in this world: PHP programmers do not want the J2EE world forced upon them. The solution for me was obvious: integrate Java support directly into PHP. I had a couple options to tackle this. I thought about writing my own library, which would use RPC or JNI calls to connect with the existing JAR file, or perhaps use an existing PECL package, but after a little research the best option was to use the open source project PHP/Java Bridge. The project had received rave reviews and in tests destroyed its competition in performance; by using it own custom protocol to facilitate data transfer.

Installation was also a breeze. Assuming you have Apache and PHP already installed, copy the appropriate .dll file from the JavaBrdige.war into extension_dir (as defined in php.ini). For convince rename it to php_java.dll.

for PHP >= 4.3.4 use php-4-java-x86-windows.dll
for PHP >= 5.0.0 use php-5.0-java-x86-windows.dll
for PHP >= 5.1.0 use java-x86-windows.dll

Next, copy JavaBridge.jar from the War file also, into the extension_dir directory. Then open the php.ini file and add the new extension, i.e.

extension=php_java.dll

That’s it, whatever jar file your going to be using, place it in the lib folder of your php installation. Restart the server and you should be good to go.

k-means and EM clustering algorithms

Sunday, April 16th, 2006

The final data mining assignment (which was due in the middle of exams) was to implement the k-means and EM algorithms in C. These are two pretty simple clustering algorithms, with k-means (or renditions of k-means) used in industry all the time. Both algorithms work in 2-dimensions and take an input file of data points separated by a space.

K-means works as follow:

  • Place K points into the space represented by the objects that are being clustered. These points represent initial group centroids.
  • Assign each object to the group that has the closest centroid.
  • When all objects have been assigned, recalculate the positions of the K centroids.
  • Repeat Steps 2 and 3 until the centroids no longer move. This produces a separation of the objects into groups from which the metric to be minimized can be calculated.

      The EM algorithm is a bit more complicated, but has generally the same idea:

      em

      Since this was in the middle of exams, I wrote both solutions (code) in one night (7pm to 3am), so no guarantee whatsoever. Take a look; if you’d change anything let me know. The code is licensed under GPL v2.

    How-to: Use __sleep() to serialize your class

    Tuesday, March 28th, 2006

    A lot of people run into this problem, and so did I when I first tried this. To make a long story short, I had a class which I wanted to serialize and store in a session variable. I would serialize the class, but when I would echo the output I’d get this:

    Code:
    N;

    This would happen regardless of what was in the class. The class used a ‘magic’ function __sleep() to close the db connection. I had read that serialize() automatically calls __sleep(), but I didn’t know is that __sleep() needed to return an array of properties of the class.

    Here is some example code to try out. Use it as is, and then comment out the contents in __sleep().

    Code:
    <?php
    
    class sleep_example {
    private $var1 = "george";
    public function __construct() {}
    
    public function __sleep() {
    return array_keys(get_object_vars($this));
    }
    }
    
    $obj1 = new sleep_example();
    $srlz = serialize($obj1);
    echo $srlz;
    
    ?>

    Hopefully you’ll read this before you waste time googl’ing and looking through PHP Bug reports..

    How-To: Set up SVN with Apache2 in Linux (Ubuntu)

    Friday, March 24th, 2006

    Initially I didn’t plan on writing anything up about this, since its pretty basic to setup. But I ran into a slight problem, which I imagine others might run into also. I guess most would have Apache running already, so all that is needed is SVN:

    Code:
    > apt-get install subversion libapache2-svn

    Say you have a domain already set up, call it abc.com. You want to be able to checkout a repository from abc.com/svn.

    Open the following file (/etc/apache2/mods-available/dav_svn.conf) in an editor and follow the instructions. In the most basic form (with no authentication) you’ll have something like this when your done:

    Code:
    < Location /abc.com/svn >
    DAV svn
    SVNPath /svn
    < /Location>

    Inside the < Location /abc.com/svn > that path must point to a directory in your web server which does NOT exist. abc.com will exist, but make sure svn doesn’t. The SVNPath will point to the actual repository which MUST be outside your web server space.

    This way, if you go to a browser and type: http://www.abc.com/svn nothing will show up, but when you checkout your repository, you will be re-directed to the actual svn directory (in this case /svn).

    Now create the SVN repository, in directory /svn

    Code:
    > svnadmin create /svn

    Be sure to change the permissions on this directory, so the web server can write to the folder:

    Code:
    > chown -R www-data /svn

    Restart Apache2:

    Code:
    > /etc/init.d/apache2 -k restart

    Now from a remote computer, you should be able to type:

    Code:
    svn co http://xxx.xxx.xxx.xx/abc.com/svn < name >

    (were xxx.xxx.xxx.xxx is your server ip and name is what you want to call the local folder)

    Why to use PEAR

    Saturday, March 11th, 2006

    A comment was posted on a tutorial I wrote How to: Install Apache, PHP, PEAR, MySQL & phpMyAdmin for Windows XP. The comment said:

    What does PEAR do that can’t be done (otherwise) … Like, I can do all the usual stuff with the database now, so am I missing anything by not installing PEAR? What does PEAR do?

    Good questions, hard to answer.  I came up with a few…

    1)

    I’m from Canada, and believe me, it gets cold up here. When it’s -20 (Celsius), I could go outside wearing a spring jacket, but the smart thing is to put a big winter jacket on. Eventually, it’ll become summer, and there is no need for a winter jacket. But as seasons are cyclical, it will become cold again. PEAR is a lot like that, you can do a lot of PEAR’s features with normal PHP, but as you use PEAR more, you’ll see it’s like wearing a winter jacket (even when you don’t have to). Plus there are so many cool packages available and in the works.

    2)

    Straight from the PEAR website it says:

    PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:

    • A structured library of open-sourced code for PHP users
    • A system for code distribution and package maintenance
    • A standard style for code written in PHP, specified here
    • The PHP Extension Community Library (PECL), see more below
    • A web site, mailing lists and download mirrors to support the PHP/PEAR community

    PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

    3)

    If you’ve ever seen Tommy Boy, you’ll know a classic line by Chris Farley:

    I can get a good look at a T-bone steak by sticking my head up a bull’s ass, but I’d rather take a butchers word for it.

    How to: Apache logging using name-based virtual hosts

    Saturday, February 25th, 2006

    I spent a bit of time today getting logging to work correctly on my server. The server is using name-based virtual hosts, so getting logging set up was going to take an extra step. The first thing was to add another LogFormat line in the apache2.conf file which would use the comonvhost option.

    Code:
    LogFormat “%v %h %l %u %t \”%r\” %>s %b \”%{Referer}i\” \”%{User-Agent}i\”" comonvhost
    LogFormat “%h %l %u %t \”%r\” %>s %b \”%{Referer}i\” \”%{User-Agent}i\”" combined
    LogFormat “%h %l %u %t \”%r\” %>s %b” common
    LogFormat “%{Referer}i -> %U” referer
    LogFormat “%{User-agent}i” agent

    Adding this LogFormat line, lets Apache distinguish between the various virtual hosts when logging. To learn more about what the options mean (i.e. %u, etc.) you can look here. Each virtual host was given its own log file, so in the VirtualHost directive, the following line was added using CustomLog:

    Code:
    ServerName www.sematopia.com
    DocumentRoot /var/www/sematopia.com
    ServerAlias sematopia.com *.sematopia.com sematopia.net *.sematopia.net
    CustomLog /var/log/apache2/sematopia/access.log comonvhost

    Then for all other VirtualHost directives, a similar line was added. Once that’s done, delete or move the old logs in /var/log/apache2. Then run:

    Code:
    apache2 –k restart

    to restart Apache. Remember, any time you delete your log files or change your apache2.conf file restart apache.

    How to: Backup MySQL database & email results using PHP

    Thursday, February 16th, 2006

    Update Aug 29: You can also try an updated version of this script that uses Amazon S3 instead of email.

    There are a bunch of scripts on the Internet that overly complicate the issue of automatically backing up your database. Here is a PHP script I wrote to backup a mysql database and email the results. Just set a cron job (/etc/crontab) to run this script with the following command: php /…./dbBackUp.php

    Code:
    < ?php
    
    /*
    
    Quickly and easily backup your MySQL database and have the tgz emailed to you.  You need PEAR installed with the Mail and Mail_Mime packages installed. Read more about PEAR here: http://pear.php.net. This will work in any *nix enviornment. Make sure you have write access to your /tmp directory.
    
    */
    
    require_once('Mail.php');
    require_once('Mail/mime.php');
    
    // mysql & minor details..
    $tmpDir = "/tmp/";
    $user = "root";
    $password = "pass";
    $dbName = "db";
    $prefix = "db_";
    
    // email settings...
    $to = "[email protected]";
    $from = "[email protected]";
    $subject = "db - backup";
    $sqlFile = $tmpDir.$prefix.date('Y_m_d').".sql";
    $attachment = $tmpDir.$prefix.date('Y_m_d').".tgz";
    
    $creatBackup = "mysqldump -u ".$user." --password=".$password." ".$dbName." > ".$sqlFile;
    $createZip = "tar cvzf $attachment $sqlFile";
    exec($creatBackup);
    exec($createZip);
    
    $headers = array('From' => $from, 'Subject' => $subject);
    $textMessage = $attachment;
    $htmlMessage = "";
    
    $mime = new Mail_Mime("\n");
    $mime->setTxtBody($textMessage);
    $mime->setHtmlBody($htmlMessage);
    $mime->addAttachment($attachment, 'text/plain');
    $body = $mime->get();
    $hdrs = $mime->headers($headers);
    $mail = &Mail::factory('mail');
    $mail->send($to, $hdrs, $body);
    
    unlink($sqlFile);
    unlink($attachment);
    
    ?>

    To download the script click here.

    XML Mail – Batch sending and easy logging

    Thursday, February 9th, 2006

    I ended up purchasing a relay service from Nettica.com, so this batch emailing idea is not going to be of much use to me. In any case, I think its a pretty good way to control emails. If your site sends many emails per day, then a batch email setup might be a good option.

    Using a batch emailing method, first off, allows for an inherent logging ability built into the process. Every time the application wants to send an email, it would write the email (XML) to send.xml. Periodically, from an internal or external server, the send.xml file is processed, and then automatically backed up. This can be extended to eventually gzip the XML files, etc.

    Secondly, if your site sends many emails, you may not want to consume resources (in real-time) sending them on demand. Instead, sending all emails every say 5 minutes, could possibly improve server performance.

    A typical example code would be:

    Code:
    $mailObj = new xmlMail();
    $mailObj->getHandle();
    $mailObj->writeEmail($to,$cc,$bcc,$from,$from,$subject,$body);
    $mailObj->closeHandle();

    See the PHP Class here for more details.

    How to: Easily parse XML with PHP

    Sunday, January 29th, 2006

    There are so many packages and scripts online to help a person parse XML. Unless your parsing some insanely complex files, there is no need. Its as easy as this:

    Code:
    $batch = new DOMDocument();
    $batch->load($this->webPath);
    $emails = $batch->getElementsByTagName("email");
    foreach( $emails as $email ) {
      $to = $email->getElementsByTagName("to")->item(0)->nodeValue;
      $cc = $email->getElementsByTagName("cc")->item(0)->nodeValue;
      $bcc = $email->getElementsByTagName("bcc")->item(0)->nodeValue;
      $from = $email->getElementsByTagName("from")->item(0)->nodeValue;
      $subject = $email->getElementsByTagName("subject")->item(0)->nodeValue;
      $body = $email->getElementsByTagName("body")->item(0)->nodeValue;
    }

    How To: Learn AJAX in 20 minutes

    Wednesday, November 9th, 2005

    Here is a quick overview and example of AJAX in action. Before you begin, this example will only work in FireFox work in FireFox and IE7. You’ll have to change few things in the JavaScript for it to work in IE6. To download the files used below click here. If you don’t have PHP/Apache installed, follow the tutorial I made to install it. The example below assumes you know the basics of PHP, you can learn as you go along if you don’t. A good reference is the base PHP website.

    AJAX stands for Asynchronous JavaScript and XML. Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

    A classic example of AJAX is Google Maps. If you havent noticed, with Google Maps you have the ability to click and drag the map. If you drag the map fast enough, you would see the new regions of the map loading in real-time. This is accomplished using AJAX.

    If you click here, you’ll see a simple example of AJAX. The example performs the multiplication of two numbers. The top form performs the calculation using AJAX, while the bottom form uses standard techniques.

    The Javascript that makes the example work is below. Basically an XMLHttpRequest is used to communicate with the server. Though the name may make you think you need to trasmit XML, it is not necessary (my example doesn’t). So when the function ajax_call() is executed, the already instantiated XMLHttpRequest attemps to open ajaxWork.php (with some parameters). Upon returning from the request (and assuming it was successful) the results are populated into the results input box.

    Code:
    var xmlhttp=false;
    
    if (!xmlhttp && typeof XMLHttpRequest!='undefined')  {
         xmlhttp = new XMLHttpRequest();
    }
    
    function ajax_call() {
         xmlhttp.open("GET", 'ajaxWork.php?num1=' +
               document.getElementById('num1').value +
                    '&num2=' + document.getElementById('num2').value , true);
    
         xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4) {
                     document.getElementById('result').value = xmlhttp.responseText;
               }
         }
    
    xmlhttp.send(null)
    return false;
    }

    Below is ajaxWork.php which is used in the Javascript above. The code below uses a PHP class called ajax that I defined in ajaxClass.php. The code creates a new instance of the class ajax, reads the parameters from the URL, performs the multiplication, and outputs the result. The results are outputed so that from the response of the XMLHttpRequest, the Javascript can update the example.

    Code:
    <?php
    
    include("ajaxClass.php");
    
    $objSem = new ajax;
    $objSem->readURLParameters();
    $objSem->staticExample();
    
    echo $objSem->result;
    ?>

    Below is the ajax class used in the PHP code above. This class is used firstly to read the parameters from the URL (via readURLParameters()) and then to perform the multiplication (via staticExample()) .

    Code:
    <?php
    
    class ajax {
    
    	var $queryParam = array();
    	var $result = 0;
    	var $num1 = 0;
    	var $num2 = 0;
    
    	function readURLParameters() {
    		$qstr = explode("&", $_SERVER['QUERY_STRING']);
    		foreach ($qstr as $value) {
    			$paramVal = explode("=",$value);
    			if (array_key_exists(1,$paramVal)) {
    				$this->queryParam[$paramVal[0]] = $paramVal[1];
    			}
    		}
    	}
    
    	function staticExample() {
    		if (array_key_exists("num1",$this->queryParam) & array_key_exists("num2",$this->queryParam)) {
    			$this->result = $this->queryParam["num1"] * $this->queryParam["num2"];
    			$this->num1 = $this->queryParam["num1"];
    			$this->num2 = $this->queryParam["num2"];
    		}
    	}
    
    }
    ?>

    The HTML is even more straightforward (so I won’t bother putting it here). You can download all the files I used here.
    Also, be sure to remember the example above will only work in FireFox. To code would be similair to work in IE6, you’d just need to change some of the Javasript. If you have any questions post a comment.

    Good luck

    How to: Install Apache, PHP, PEAR, MySQL & phpMyAdmin for Windows XP

    Sunday, October 9th, 2005

    I’ve had lots of people ask my in the past, how to install PHP, MySQL and Apache for Windows XP. I recently formated my computer, and since I was going to do it, I thought I’d write out how to do this, for anyone who wants to know. My computer has SP2 installed.

    Apache Web Server

    Download Apache HTTP Server. I downloaded the current stable release, in this case: Apache 2.0.54. So download the Win32 Binary (MSI Installer), double click it, let it install.

    PHP Run-time

    Download PHP. I downloaded PHP 4.4.0. I could have downloaded PHP 5.0, but as long as PHP < 5.0 gives me what I need, I won’t change. PHP 5 is the way to go. The tutorial below is pretty much the same, see the comments if you have problems. Unzip the contents, and put it all in the folder C:\php.
    Copy the following files into your Apache2 installation directory. In my case it was C:\Program Files\Apache Group\Apache2.

    Code:
    php4ts.dll
    php4apache2.dll
    php.ini-recommended

    Rename php.ini-recommened to php.ini. Open the php.ini in your favorite editor. Mine is EditPlus.

    Search for ‘doc_root’ until you find the line:

    Code:
    doc_root =

    Change this line to (in my case):

    Code:
    doc_root = C:\\Program Files\\Apache Group\\Apache2\\htdocs

    Go to the directory: C:\Program Files\Apache Group\Apache2\conf\;
    Add the following lines to the end of the file httpd.conf:

    Code:
    LoadModule php4_module php4apache2.dll
    AddType application/x-httpd-php .php

    In the same file, add index.php to DirectoryIndex — this will make sure index.php will be picked up by the server automatically:

    Code:
    DirectoryIndex index.html index.html.var index.php

    PEAR Extension

    PEAR is an extension for PHP. These days PEAR is included with PHP, but you need to install it yourself. I use PEAR on all my PHP developments.

    Ok.. Installing PEAR isn’t bad, here is what you do:

    Open a command line window (i.e. Start->Run->cmd)
    Go to the PHP directory, in my case C:\php. Type go-pear.bat. Follow the instructions.
    The PEAR extension get installed in C:\php\PEAR directory.
    Once PEAR is installed, go to the php.ini file in your Apache2 directory. Find the

    Code:
    ;include_path = ".;c:\\php\\includes"

    Remove the semi-colon (to un-comment it), and then add C:\php\PEAR to it

    Code:
    include_path = ".;c:\\php\\includes;C:\\php\\PEAR"

    MySQL DataBase

    Download MySQL (runtime) and MySQL Administrator (Admin program). I used MySQL 4.1 Generally Available (GA) release. Download, unzip, and install both.

    Testing it all – you really don’t need to, but before testing, restart your computer.

    Test Apache Web Server

    Once Apache is installed, you should be able to go to your favorite browser, type the following URL: http://localhost/ and have a test page load.

    Test PHP

    Go to the htdocs folder in Apache2 folder
    Create a file called index.php, inside of that file put (be sure to remove the space between the < and the ?php):

    Code:
    <?php
    echo "php installed ok";
    ?>

    Go to your browser, type the following URL: http://localhost/index.php
    If everything worked OK, “php installed ok” will appear on the screen.

    Test MySQL and PHP using phpMyAdmin

    Download phpMyAdmin.
    This is the best web based MySQL Administration Tool (vital, trust me).
    Unzip the contents into a folder phpMyAdmin in your htdocs folder.
    Were going to use phpMyAdmin to control MySQL instead of the command line.
    In the phpMyAdmin folder open the config.inc.php and type in the your root password for MySQL:

    Code:
    $cfg['Servers'][$i]['password'] = 'xxxxx';

    Try and run phpMyAdmin in your browser: http://localhost/phpMyAdmin/
    You’ll most likely get the error:

    Client does not support authentication protocol requested by server; consider upgrading MySQL client

    To fix this, do the following:

    1. Start the MySql Administrator, select “Startup Variables” from the menu, select the “Security” Tab. Check ‘Use old passwords’.
    2. Select “User Administration” from the menu, select the root user account and change the password for root user (other than null)
    3. Select “Service Control” from the menu, press “Stop Service” button and then press “Restart Service”.

    Go back to config.inc.php and type in the your new root password for MySQL:

    Code:
    $cfg['Servers'][$i]['password'] = 'yyyyyy';

    Try and run phpMyAdmin: http://localhost/phpMyAdmin/ — this should work now.

    Test PEAR

    Using phpMyAdmin to create a database
    In your htdocs folder create a file called testpear.php, in the file put the following (be sure to remove the space between the < and the ?php):

    Code:
    <?php
    
    require_once 'DB.php';
    PEAR::setErrorHandling(PEAR_ERROR_DIE);
    
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = 'password';
    $db_name = 'dataBase_name';
    $dsn = "mysql://$db_user:$db_pass@unix+$db_host/$db_name";
    
    $db = DB::connect($dsn);
    $db->setFetchMode(DB_FETCHMODE_OBJECT);
    
    ?>

    This will use the PEAR DB Extension to create a connection to your database. Before running this file make sure your database details are correct (i.e. name, user, password). Run this file in your browser, if no errors are listed, then your good to go.

    ————————

    Sources

    http://forums.mysql.com/read.php?11,6400,38314#msg-38314

    http://www.devarticles.com/c/a/Apache/Installing-PHP-under-Windows/

    How To: Making an independant copy of a JavaScript array

    Wednesday, August 31st, 2005

    In JavaScript, if you want to make an independent copy of an array, use the Array slice() function, as seen below

    Code:
    // JavaScript syntax
    var landArray = new Array("Asia", "Africa");
    var continentArray = landArray;
    landArray.push("Australia"); // this also adds "Australia" to continentList
    

    To create a copy of an array that is independent of another array:
    Use the Array object’s slice() method.

    For example, the following statements create an array and then use slice() to make an independent copy of the array.

    Code:
    // JavaScript syntax
    var oldArray = ["a", "b", "c"];
    var newArray = oldArray.slice(); // makes an independent copy of oldArray
    

    After newArray is created, editing either oldArray or newArray has no effect on the other.
    Save you time and effort to make an independant copy.