AMFPHP 1.0 Ready

AMFPHP (Flash Remoting written in PHP) has hit a stable version 1.0 release! I’ve been looking forward to this for a long time.

Flash Remoting is a method of transfering data to a Macromedia Flash Movie. It sends it in binary format and is much easier to use as it arrives in an object form, meaning, you don’t have to sort through the child nodes of an XML object. I have been using AMFPHP for over a year on several projects (being one of the main backend developers in my company, mediaRAIN) to send stuff. I created the logo storage of LogoMaker/InstaLogo using AMFPHP which handles, and I quote, “a lot.” Actaully, in July we got 4.4 million posts to the remoting service. I suppose that’s on average almost 100 a minute! We’ve also used remoting in several other applications.

I’ve been pretty pleased just with the ability to pass data back an forth from Flash to PHP. The only things that bothered me was the beastly methodTable array the PHP service needed and the design issue in which your Flash objects are converted into associative arrays in PHP rather than PHP objects. The methodTable is now created using reflecting and JavaDoc style documenting (very nice) and as for the array vs object issue, well, I made a hack for that myself in our version of the remoting. Associative arrays are “more natural” in PHP, and you can use the methodTable to define custom object types. Well, not recursively, however, you can now be able to associate a PHP class with a Flash class in version 1.0. Really nice feature. Kudos to all of those who have helped develop PHP remoting for Flash. You can see all of the new features in 1.0 yourself, but it’s faster, more organized, more features, and the whole bit.

Pherret currently can be integrated with Flash Remoting and will have full support as an extra module. mediaRAIN is all about Flash, so of course I had to take that into consideration as I built Pherret. But you have a truer Model View Controller (MVC) system when you can use different views (HTML or Flash) or controllers and the same model.

From Text to Node

I have created a method that assists in creating your HTML elements in Javascript. textToNode takes a string of text and converts it into a DOM element which you may then use for insertion. It’s much easier to use than creating each node seperately, adding attributes to it, then appending it to the parent. It also works for table elements (tr, td, etc.) and the option element in a drop-down box.

This was created for DOMClass objects but has been very nice for creating elements on the fly. It is as easy to use as the innerHTML property of an element, but it works with table elements etc. and gives you the node reference which you may then attach code to as needed.

Javascript is beautiful.

function textToNode(text) {
	var type = text.match(/<(\w+)/)[1];
	var container = document.createElement('div');
	var elem;
	switch (type) {
		case 'thead':
		case 'tfoot':
		case 'tbody':
			container.innerHTML = '<table>' + text + '</table>';
			elem = container.firstChild.firstChild;
			break;
		case 'tr':
		case 'th':
			container.innerHTML = '<table><tbody>' + text + '</tbody></table>';
			elem = container.firstChild.firstChild.firstChild;
			break;
		case 'td':
			container.innerHTML = '<table><tbody><tr>' + text + '</tr></tbody></table>';
			elem = container.firstChild.firstChild.firstChild.firstChild;
			break;
		case 'option':
			container.innerHTML = '<select>' + text + '</select>';
			elem = container.firstChild.firstChild;
			break;
		default:
			container.innerHTML = text;
			elem = container.firstChild;
	}
	return elem;
}

First I check what type of element this is using a regular expression. Then I make a container to put my innerHTML in. Following is a switch statement to handle the special types that can’t be created using innerHTML unless inside of their native element. I assign the target node to the elem variable and then return it after the switch statement. Pretty simple, really nice to use.

setProperties

One of the simple and very useful pieces of code in Pherret (a PHP 5 framework) is the setProperties() function in the base Object class. The name originally came from Java Beans and works in a similar manner. I’m sharing it because it could be used in any code with PHP 5 or PHP 4. First, here is the problem being solved. Do you ever find yourself setting and object (or array, or variables) from a HTTP post in the following manner?

 $user = new User(); $user->firstName = $_POST['firstName']; $user->lastName = $_POST['lastName']; $user->address = $_POST['address']; $user->city = $_POST['city']; $user->state = $_POST['state']; $user->zip = $_POST['zip']; $user->email = $_POST['email']; // validate the data $user->saveToDatabase(); 

Don’t you think it would be easier to do this?

 $user = new User(); $user->setProperties(); // validate data $user->saveToDatabase(); 

This can be done by having the User class extend the Object class. The Object class has a method called setProperties($params = $_REQUEST, $properties = '*', $prefix = '', $force = false) which by default sets all the properties that an extending object has from the $_REQUEST. There are many other ways you can use this method. You can set another source to populate your object from, including $_GET, $_POST, another array or even another object. You may also limit which properties are set by passing them into the $properties parameter in a comma delimited list. To set all properties you pass '*'. To set only some you would pass 'prop1, prop2, prop3.' If you want _all_ the properties set except one or two you may add a negative sign in front of the property like '*, -prop1, -prop2', '*' says use all, then the '-prop1,-prop2' would exclude those properties. In addition you may add a $prefix to the properties. This is useful if you have two objects and want to set both properties this way (ie. firstName, shipFirstName, billLastName). It takes care of the camel-case for you. And finally, there is the $force parameter. The default is false which means that only properties currently in the object will be set from items in the $params array/obj. By setting $force to true you may force all items to be set on the object. This is useful when you have an empty object, or one that has no class definition. Now, here is what you’ve been waiting for. The setProperties method to add to any class (or even better, any parent class).

 function setProperties($params = null, $properties = "*", $prefix = "", $force = false) { if (is_object($params)) { $params = get_object_vars($params); } elseif (empty($params)) { $params = $_REQUEST; } elseif (!is_array($params)) { //throw new Exception('The $params sent to setProperties is niether an object or an array (and it should be)'); return; } $props = explode(",", str_replace(" ", "", $properties)); $properties = array(); foreach ($props as $prop) { if ($prop == '*') { $properties = $force ? $params : get_object_vars($this); } elseif ($prop{0} == '-') { unset($properties[substr($prop, 1)]); } else { $properties[$prop] = 1; } } foreach ($properties as $prop => $value) { $prop = ($prop{0} == '_' ? substr($prop, 1) : $prop);
$param = empty($prefix) ? $prop : $prefix . ucfirst($prop); if (array_key_exists($param, $params)) { $setter = "set" . ucfirst($prop); $this->$setter($params[$param]); } } } function getProperties() { return get_object_vars($this); } 

I threw in the bonus getProperties() function :) I hope this can save at least one developer some repetative coding in their application.

Class for the DOM

It’s alive!! I have created a very cool, very simple, function to create new javascript objects that are (not just act upon) HTML DOM elements. Let me explain. Say I have a cool new tree menu I’m creating (true story), and I want others to be able to just start creating the menu items and adding them in via javascript if they need to. The ideal way would be to just say myItem = new MenuItem(‘Cool Item’); and have it return to me the actual menu item (the TR tag or LI tag) which can be inserted into the menu.

No more of this element wrapper stuff. I don’t want to code my classes to act upon a DOM element. I want to write them as if they actually are the DOM element, just a specialized one. This makes much more sense to me as I am working with the objects of the DOM.

Here is the code:

var DOMClass = {
    create: function(element) {
        return function() {
            var div = document.createElement('div');
            div.innerHTML = element;
            var elem = div.firstChild;
            delete div;
            for (var property in this) {
                elem[property] = this[property];
            }
            if (this.initialize) elem.initialize.apply(elem, arguments);
            return elem;
        }
    }
};

You can just add this to your Prototype library or something. Then start making your components.

The way to use this is pretty straightforward. First, you create a new “class” like so:

MySentence = DOMClass.create('This is my <strong>great</strong> text');

MySentence.prototype = {
    initialize: function() {
        for (var i = 0; i < this.childNodes.length; i++) {
            if (this.childNodes[i].nodeName == 'STRONG') {
                this.word = this.childNodes[i];
            }
        }
    },
    rewrite: function(word) {
        this.word.innerHTML = word;
    }
};

Let’s walk through this step by step. First, I create a new class called MySentence. It will be a paragraph element and it will have some text inside of it (the contents are not required). Simple enough. I can then declare my prototype for the class which will contain all the methods of my new class, including an initialize method which will be called if it exists. In the initialize method I find the STRONG tag and assign it to the property “word” for use in my other method, rewrite. That method just changes the word inside the STRONG tag. I now have a class that when created, will be a paragraph with some <strong>great</strong> text inside of it and a method to rewrite the word “great.” You may even try it out and see it working in action. Here is a fun test:

window.onload = function() {
    var s = new MySentence();
    document.body.appendChild(s);
    s.onclick = function() {
        this.rewrite('pretty good');
    }
};

Putting all of the above code in a HTML page will give you some text that when clicked on, will change the wording. Pretty useful huh! Ok, so maybe this particular example isn’t uber useful, but coding new objects, widgets, and components might be easier. At least a little bit. You may see the above example in action.

I’ll see what I can add onto this to make it better. Perhaps something where you can access the tags inside by saying this.word = this.strong[0]; instead of having to loop through all the children.

This class works for both IE 6 and Firefox. I would be very interested to know how many other browsers it worked on.

I have another javascript goody that my friend Derek and I worked on together which is pretty cool. I’ll share that soon too.

Creating Objects (4 of 5)

This is the fourth of five articles on object oriented-programming.

In the previous three object oriented programming articles written for jacwright.com, we introduced object oriented programming, spoke of thinking about a system object oriented, and discussed the importance of planning, even if only in one’s head. The next two articles, Creating Objects and Reusing Objects, delve into the meatier subject of writing objects. We will be discussing how to implement the plans we’ve made and the systems we’ve conceptualized. Without these principles, object oriented programming can become a mess instead of a blessing.

Encapsulate, Encapsulate, Dance to the Music (lyrics)

Encapsulation means keeping your business to yourself. Objects can’t be bothering others with their issues. Other objects have their own stuff to worry about. When we create an object it needs to have methods for other objects to speak with it, but it should rely on others as little as possible. There are two terms we use to describe how encapsulated an object is: “black box” and “white box“. Black box describes an object that is completely encapsulated, closed up, secretive. We don’t know anything that’s going on inside of this type of object. We also can’t see anything inside it. We must ask it for anything and everything we want to know about it. For example, a black box object has “getters” and “setters” to access it’s properties. A getter or setter is simply a method that returns the object’s properties. So instead of looking at the object’s properties directly, we must request the properties through these methods. White box describes an object that is not quite so into security. It doesn’t care if other’s know what it likes for breakfast or it’s favorite color. Often we access it’s properties direc tly. It may also require us to know more about it in order to use, making it not as easy to use. It may be more needy than a black box object, wanting us to find out about it. We may need to pass it’s properties around to it’s methods and/or call several of its methods to accomplish one task.

It’s Not Just Black and White

Although these terms, black box and white box, help give us a way to describe objects, it’s not so black and white. There are varying shades of gray in between. But black box is best, right? Well, again, things aren’t so simple. Writing a black box objects means that we need to take more time to write it’s getters and setters and make sure only necessary methods are publicly accessible. White box objects can be quicker to build and give us more control over the object. They also don’t have to be written to be needy. Black is generally more user friendly (because we don’t need to know more than we have to) and white is generally more flexible (because we have more control outside the object). When is a good time to use black box, and when should we use white box then? Good question, glad I asked. If we are creating an object that we will be releasing to the world, or an object that is going to be reused over and over, or an object that we want to be used in just the right way and not any other, we would probably go with a darker shade of box. If the object in question is only going to be used once, if it will only be used by us, or if we want the object to be as flexible as possible.

Extend

Extending an object is having sub-objects based off of the parent. It helps us reuse code, but at the expense of greater portability. We may have a person class with child classes extending it of customer and employee. We may put the similar code in person that customer and employee both share, such as name, address, and a method to store the object. We can then put the unique code in the child classes. Employee will have payroll information and maybe a method to give a bonus. Customer will have a shopping cart and maybe an account. Extending is a great way to reuse code, and it makes good sense. We are able to reuse code effectivly between related objects, and if there needs to be a change (for example, we now want to keep track of first name and last name seperatly for all people in our database) then we only need to change it in one place. We also can make the child objects fully black box so that nothing need be known about it. However, if we ever wanted to use our Employee class in another system, we would need to make sure we brought it as well as it’s parent class, Person, over to the new system.

Beware Family Trees

There is a caution to be added here. It may sometimes become tempting to create whole family trees, reusing code from the whole system. This is generally a bad idea. Inheritance may work best when it is only a few generations. The reason for this is simple. As stated above, if we wanted to reuse an object in another system, we would have to bring the whole tree over with the object. It also can start to become confusing with so many classes dependant on others. The only time I would suggest extending more than a few generations is when creating a system such as a framework, a component set, a module or something else that would always be packaged together. Even in these situations, there may be a better way to use functionality if it makes sense, and that is object composition.

Compose

Object composition is another way to reuse code. Unlike extending where we inherit methods and properties from parent classes, with composition we make an object with other objects. This could be likened to the human body, one complete object made up of many other objects. The body ties everything together, helping the heart, the braing, the lungs to all work together. The customer’s shopping cart in the previous example could become a seperate object that belongs to the customer. This may make more sense, to keep objects more simple. It increases organization. Of course, like anything else, to much of a good thing can be bad. We wouldn’t want the customer to have a name object which contains his first name and last name. We would start to have more objects than we knew what to do with if we were breaking them down so small. Composition is used very often, most any object oriented programs. Larger objects are made up of smaller pieces. It also can be more reusable. The employee object could be used without needing his payroll object and other (non-essential) objects that make him up.

Object Creation

Creating objects is a balancing act. Many decisions are made (often subconsiously) about how encapsulated to make an object, how to extend it, and how to compose it. The road to becoming proficient at object oriented programming may often start out with too few of these principles implemented. Then, once they are learned, it may become overused, making systems too complex. Finally, a middle ground will be found when it is remembered that the underlying purpose of object oriented programming is not to reuse but to simplify and organize.

Coming Soon

I have been working on a project recently which has had a shorter than comfotable deadline (working long hours, weekends, etc.). For this reason I haven’t had time to upkeep the site as I would like. The information on Pherret is outdated, and there is not a good (recent) download of the framework. However, for better or for worse, the deadlines are coming this week and the following. Because of this there will not be any article this week. I hope to be able to get back on top of things at the end of this week or the end of next week. I should be able to update the information, perhaps even get some documentation going, and put some downloads of Pherret and Arras up. Thank you for your patience!

« Previous Page — Next Page »