Monday, June 30, 2008

Ajax or JavaScript sub domain request

Some time we could have a situation like this one:

  • a site in a sub domain, called http://a.test.com

  • another site in another sub domain, called http://b.test.com

  • of course, a generic main site, called http://test.com


A common problem between one or more sub domains, is the possibility to use, or call, scripts in the main domain, because of security restrictions.

The simplest solution is to force, in the client side, the document.domain, specifying the common one, i.e.

dcument.domain = "test.com";

In this way you can add, for example, an iframe, and read its content, or use parent window object from the iframe that points, for example, to http://test.com

There are different reasons to do it, and one of them, is the ability to share a global, or common, space, between every sub domain, performing Ajax requests or whatever else we need.

This object, saved in http://test.com, and loaded by every other sub domain, like "a" or "b", could solve in a really simple way this problem.

CrossDomain = function(){
// webreflection.blogspot.com - Mit Style License
var uid = 0, iframe, unset;
return {
get:function(location){
for(var
search = location.search.substring(1).split("&"),
i = 0,
length = search.length,
value;
i < length;
i++
){
value = search[i].split("=");
if(value[0] === "uid"){
search = this[value[1]];
delete this[value[1]];
return search;
}
}
},
unset:function(){
document.domain = unset;
return this;
},
send:function(domain, value){
var id = Math.random() + "." + uid++;
this[id] = value;
if(!iframe){
(document.body || document.documentElement).appendChild(
iframe = document.createElement("iframe")
).style.position = "absolute";
iframe.style.width = iframe.style.height = "1px";
iframe.style.top = iframe.style.left = "-10000px";
};
iframe.src = domain + (~domain.indexOf("?") ? "&" : "?" ) + "uid=" + id;
return this;
},
set:function(){
if(!unset)
unset = document.domain;
document.domain = unset.split(".").slice(1).join(".");
return this;
}
}
}();

Its usage is really simple, and here there is an example from, as example, a.test.com:

// callback to call (if it is the same for other sub domains
// put them in an external file
function showMessage(message){
document.body.appendChild(document.createTextNode(message));
};

// set domain name, i.e. test.com
CrossDomain.set();

// call the page sending some value, every kind of value we need
CrossDomain.send("http://test.com/", ["a", "b", "c"]);


On the other file, the index inside test.com, we could simply use this piece of code:

// set domain name, manually or including CrossDomain
// and using its set method
document.domain = "test.com";

// call, simply, the parent function
// using the get method to avoid conflicts
// with multiple requestes
parent.showMessage(
"You sent me " + parent.CrossDomain.get(location)
); // will alert a,b,c

The good thing of this simple created bridge, is that once you are in test.com, from a.test.com or b.test.com, you can call via Ajax every page inside test.com, sharing a single folder inside the global domain, instead of copy the same stuff everywhere in other domains.

// set domain name
document.domain = "test.com";

// simple Ajax request
var xhr = new XMLHttpRequest;
xhr.open("get", "?demo", true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4)
parent.showMessage([
"You sent me " + parent.CrossDomain.get(location),
"And AJAX said " + xhr.responseText
].join("\n"));
};
xhr.send(null);


I hope this will be useful :)

Sunday, June 22, 2008

From the future, a PHP JavaScript like Number class, with late static binding and operator overloading

PHP and operator overloading


Not everyone knows that with PHP, and since 2006, it is possible to implement operator overloading, thanks to a PECL extension.
One common PHP VS other language flame, is about PHP poor OOP expressiveness and power.
Another common request from skilled PHP developers, is the possibility to create a class that is able to manage every situation during code execution.
For example, try to think about a Number class, and try to use every native Magic method to perform a simple task like this one:

$i = new Number(123);
$i += 2;
echo $i; // 125

Above code is simply not implementable with current version of PHP 5.2 or greater, if we do not install php_operator.so or .dll.
Unfortunately, this extension is still experimental, and not documented at all.
That is why I have created a full class, based entirely on this extension, and for this post only, compatible with PHP 5.2 (then, without usage of late static binding).

The JavaScript like Number class


Next code, is a complete example of how we could implement operator overloading, to perform every kind of task operator related:

/** JavaScript Number like class
* @author Andrea Giammarchi
* @site webreflection.blogspot.com
* @license Mit Style
*/
class Number {
protected $__value__;
public function __construct($__value__ = 0){
switch(true){
case intval($__value__) == $__value__:
case floatval($__value__) == $__value__:
$this->__value__ = $__value__;
break;
default:
$this->__value__ = (int)$__value__;
break;
}
}
public function __add($__value__){
return new Number($this->__value__ + Number::__value__($__value__));
}
public function __sub($__value__){
return new Number($this->__value__ - Number::__value__($__value__));
}
public function __mul($__value__){
return new Number($this->__value__ * Number::__value__($__value__));
}
public function __div($__value__){
return new Number($this->__value__ / Number::__value__($__value__));
}
public function __mod($__value__){
return new Number($this->__value__ % Number::__value__($__value__));
}
public function __sl($__value__){
return new Number($this->__value__ << Number::__value__($__value__));
}
public function __sr($__value__){
return new Number($this->__value__ >> Number::__value__($__value__));
}
/* in this class, same behavior of __toString
public function __concat($__value__){
return (string)$this->__value__.$__value__;
}
#*/
public function __bw_or($__value__){
return new Number($this->__value__ | Number::__value__($__value__));
}
public function __bw_and($__value__){
return new Number($this->__value__ & Number::__value__($__value__));
}
public function __bw_xor($__value__){
return new Number($this->__value__ ^ Number::__value__($__value__));
}
/* extension error. Anyway, in this class, it is not implemented - two (new Number) are always different
public function __is_identical($__value__){
return $this === $__value__;
}
public function __is_not_identical($__value__){
return $this !== $__value__;
}
#*/
public function __is_equal($__value__){
return $this->__value__ == Number::__value__($__value__);
}
public function __is_not_equal($__value__){
return $this->__value__ != Number::__value__($__value__);
}
public function __is_smaller($__value__){
return $this->__value__ < Number::__value__($__value__);
}
public function __is_smaller_or_equal($__value__){
return $this->__value__ <= Number::__value__($__value__);
}
/* waiting for the patch
public function __is_greater($__value__){
return $this->__value__ > Number::__value__($__value__);
}
public function __is_greater_or_equal($__value__){
return $this->__value__ >= Number::__value__($__value__);
}
#*/
public function __bw_not(){
return new Number(~$this->__value__);
}
/* undefined behaviour, waiting for documentation
public function __bool(){
return $this->__value__ != 0;
}
public function __bool_not(){
return $this->__value__ == 0;
}
#*/
public function __assign_add($__value__){
$this->__value__ += Number::__value__($__value__);
return $this;
}
public function __assign_sub($__value__){
$this->__value__ -= Number::__value__($__value__);
return $this;
}
public function __assign_mul($__value__){
$this->__value__ *= Number::__value__($__value__);
return $this;
}
public function __assign_div($__value__){
$this->__value__ /= Number::__value__($__value__);
return $this;
}
public function __assign_mod($__value__){
$this->__value__ %= Number::__value__($__value__);
return $this;
}
public function __assign_sl($__value__){
$this->__value__ <<= Number::__value__($__value__);
return $this;
}
public function __assign_sr($__value__){
$this->__value__ >>= Number::__value__($__value__);
return $this;
}
public function __assign_concat($__value__){
throw new Exception('unable to concatenate "'.$__value__.'" with a value of an instanceof '.Number);
}
public function __assign_bw_or($__value__){
return new Number($this->__value__ | Number::__value__($__value__));
}
public function __assign_bw_and($__value__){
return new Number($this->__value__ & Number::__value__($__value__));
}
public function __assign_bw_xor($__value__){
return new Number($this->__value__ ^ Number::__value__($__value__));
}
public function __pre_inc(){
++$this->__value__;
return $this;
}
public function __pre_dec(){
--$this->__value__;
return $this;
}
public function __post_inc(){
return new Number($this->__value__++);
}
public function __post_dec(){
return new Number($this->__value__--);
}
public function __toString(){
return (string)$this->__value__;
}
static protected function __value__($__value__){
return $__value__ instanceof Number ? $__value__->__value__ : $__value__;
}
public function toExponential($decimal = 0){
return sprintf(func_num_args() ? '%.'.$decimal.'e' : '%e', $this->__value__);
}
public function toFixed($decimal = 0){
return (string)(0 < func_num_args() ?
round($this->__value__ * ($decimal = pow(10, $decimal))) / $decimal :
round($this->__value__)
);
}
public function toPrecision($decimal = 0){
if(0 < func_num_args()){
$length = strlen((int)$this->__value__);
if($decimal < $length)
$result = $this->toExponential($decimal);
elseif(strlen($this->__value__) <= $decimal)
$result = str_pad($this->__value__, $decimal, '0', STR_PAD_RIGHT);
else
$result = $this->toFixed($decimal - $length);
}
else
$result = (string)$this->__value__;
return $result;
return sprintf(func_num_args() ? '%.'.$decimal.'e' : '%e', $this->__value__);
}
public function toLocaleString(){
return is_int($this->__value__) ?
(string)$this->__value__ :
number_format($this->__value__, strlen($this->__value__) - strpos($this->__value__, '.') - 1)
;
}
public function toSource(){
return 'new Number('.$this->__value__.')';
}
public function toString(){
return (string)$this->__value__;
}
public function valueOf(){
return $this->__value__;
}
}

With above class we can use type hint checks with functions or method:

function atLeastOne(Number $total){
return 0 < $total;
}

if(atLeastOne(new Number(1)))
echo 'here we go';

We can do almost everything we could do with a primitive int or float value, but we have methods too, while we cannot implement them in a primitive value:

$f = new Number(123);
$f += new Number(0.345);
echo $f->toFixed(2); // 123.35

This case is about numbers, but nothing block us to create classes like, for example, a Date one, where to know the difference between two dates you could simply do:

echo new Date() - new Date($twohoursago); // 7200


The introduction of late static binding


The biggest limit ever, in PHP OOP, is the implementation of self keyword, that does not allow us to extend easily a class.
For example, the Number class, cannot be extended in a reasonable way, because since every method use static public self::__value__ one to get correct information from received value, we should override every method to let them point into different static one.
Indeed, it is natural to think about an Int, and a Float class, but we cannot create them quickly and logically, while using this Number class implementation from the future it is possible to create Int and Float in few lines of code:

class Int extends Number {
static protected $__CLASS__ = __CLASS__;
public function __construct($__value__ = 0){
$this->__value__ = static::__value__($__value__);
}
static protected function __value__($__value__){
return intval($__value__ instanceof Number ? $__value__->__value__ : $__value__);
}
}

class Float extends Number {
static protected $__CLASS__ = __CLASS__;
public function __construct($__value__ = 0){
$this->__value__ = static::__value__($__value__);
}
static protected function __value__($__value__){
return floatval($__value__ instanceof Number ? $__value__->__value__ : $__value__);
}
}


GO, OPERATOR, GO!!!


We have just seen that operator overloading could open a lot of doors for PHP OOP development, and as is for the SPL, the best thing PHP developers have done since PHP 5 release, and as was for the Go, PHP5 Go!!! period, I do like to be able to create classes that are powerful, expressive, and without boring limits for our fantasy, control, and finally to let us be truly proud to develop with such amazing language. Next step? A mix of runkit extension, operator, and SPL, to create a real JavaScript implementation in pure PHP ( how could I call them, Phino? )

Saturday, June 21, 2008

Lazy developers, Stack concept, and the fastest, unobtrusive, JavaScript StringBuilder

Fast Web, and lazy developers


About 1 month ago, I have posted a little piece of code that, in some way, could be a little revolution for JavaScript 3rd edition, and every kind of library.
I explained how to use native Array methods with an object, to extend Array itself, or simply create a Stack behaviour, compatible with every used browser.
Few comments a part, in both Ajaxian and this site, it seems that nobody had enough fantasy to use that tricky piece of code to create every kind of Stack based constructor, library, or Iterator, without destroying the native Array.prototype. So, here I am, with another little piece of code that uses the same Stack concept to create a StringBuilder constructor.

The Fastest Unobtrusive JavaScript StringBuilder


A common problem with JavaScript and, specially, Internet Explorer, is string concatenation.
You can find every kind of benchmark, even in IEBlog, about string concatenation problems.
IE Team seems to suggest the usage of an Array, because it is much faster than plus operator, i.e.

"a" + "b" + "c"
// slower than
["a", "b", "c"].join("")

Different libraries, and different developers, use daily a StringBuilder like constructor, to perform string concatenation and finally create resulted string.

You can find different implementation, and someone is better for some feature than another one, but every implementation is not using the Stack constructor trick:

function StringBuilder(){
// (C) Andrea Giammarchi - Mit Style License
if(arguments.length)
this.append.apply(this, arguments);
};
StringBuilder.prototype = function(){
var join = Array.prototype.join,
slice = Array.prototype.slice,
RegExp = /\{(\d+)\}/g,
toString = function(){return join.call(this, "")};
return {
constructor:StringBuilder,
length:0,
append:Array.prototype.push,
appendFormat:function(String){
var i = 0, args = slice.call(arguments, 1);
this.append(RegExp.test(String) ?
String.replace(RegExp, function(String, i){return args[i]}):
String.replace(/\?/g, function(){return args[i++]})
);
return this;
},
size:function(){return this.toString().length},
toString:toString,
valueOf:toString
}
}();

Above constructor is fast as is Array one, when you use them to push values inside the stack. In few words, there's nothing faster to do this simple task, than a native method as push is.

var str = new StringBuilder("a", "b", "c");
str.append("de", "f");
alert(str.length); // 5
alert(str.size()); // 6, the length of the string
alert(str); // abcdef

You can use a StringBuilder instance inside append method without problems, as you can use plus operator to simply create a String, even if it does not make sense

alert(new StringBuilder("abc") + new StringBuilder("def"));
(str = new StringBuilder("abc")).append(new StringBuilder("def"));
alert(str);

Finally, you can use a simplified version of the appendFormat method too:

alert(
new StringBuilder("a", "b", "c").
appendFormat("{0}{1}{0}", 0, 1).
appendFormat("???", 1, 2, 3)
);
// abc010123


What's next?


We can use Stack and/or ArrayObject constructors, or concepts, to literally create every kind of FILO/LIFO/LILO/FIFO based constructor, and without modifying the native Array.prototype.
It is simply up to you, but what I am already working over is:

  • a generic Collection constructor, with predefined Type (new Collection(Person), to have a Collection of Persons, for example)

  • a Matrix manager, which aim is to become the fastest one, with JavaScript

  • something else ... so please, stay tuned ;)

Thursday, June 19, 2008

A completely revisited Singleton and Factory design pattern for PHP and JavaScript

Singleton


From Wikipedia
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. It is also considered an anti-pattern by some people, who feel that it is often used as a euphemism for global variable

Basically, the last point is true.
Whatever we think about Singleton, we cannot say that we do not use this pattern to have the same instance, or object, in every place of our application.
The most common case scenario, is usually a database object, or a global queue, used as a stack, or something similar, like a template engine instance or a DOM / XML node.
The worst thing ever, is that with languages like PHP and JavaScript, the Singleton pattern is really hard to implement correctly.

Why bother with a class?


In a lot of frameworks, as in a lot of libraries, I have seen every kind of Singleton implementation, and most of them, are conceptually hilarious.

// PHP Singleton classic example
Singleton::load('MyCLassName');
MyClassName::getInstance();

// JavaSript classic example
MyConstructor.getInstance();
// where in different cases, getInstance
// is not even defined inside a closure
// to preserve singleton integrity ...
// ... but does exist a way to make
// a JS constructor private? NO

With PHP, problems are different:

  • if there's no magic __clone method, it does not make sense

  • if you serialize and unserialize objects, it could not make sense

  • if you create a Singleton class, it is nearly impossible to extend correctly its behaviour (come on lazy binds and PHP 5.3!!!)

  • if you try to create a __callStatic method, you simply have to wait next PHP release


In PHP again, as is for JavaScript, outside a closure, every static function is global.
This means that we do not need to use global something, in PHP, and we do not use, usually, window as prefix to use declared function.
It is true, the most horrible piece of code you can spot in an entire PHP application, is the usage of global keyword to transport variables everywhere.
We do not need that, and we can have a Singleton behaviour, simply using a function !!!

function Singleton($__CLASS__){
// webreflection.blogspot.com
static $list = array();
if(!isset($list[$__CLASS__])){
$arguments = func_get_args();
array_shift($arguments);
$instance = new ReflectionClass($__CLASS__);
$list[$__CLASS__] = $instance->getConstructor() ? $instance->newInstanceArgs($arguments) : $instance->newInstance();
}
return $list[$__CLASS__];
}

Is static variable private inside function scope? Yes
Is this function smarter than a public static method? Yes

class A {
protected $value = '123';
function write($what){
echo $what.$this->value;
return $this;
}
}
class B extends A {
function __construct($value){
$this->value = $value;
}
}
echo '
', var_dump(Singleton('A') === Singleton('A')), '
';
echo '
', var_dump(
Singleton('B', 'my value')->write('Hello World') === Singleton('B')
), '
';
// true, Hello Worldmy value, true

Do you really want a class?


Ok, somebody could thing that above function is pointless, so here there is a class that will use the same function.

class Singleton {
// webreflection.blogspot.com
private $_class,
$_instance;
public function __construct($__CLASS__){
$arguments = func_get_args();
$this->_class = new ReflectionClass($this->_instance = call_user_func_array('Singleton', $arguments));
}
public function __get($property){
return $this->_instance->$property;
}
public function __call($method, array $arguments){
return $this->_class->getMethod($method)->invokeArgs($this->_instance, $arguments);
}
public function __set($property, $value){
$this->_instance->$property = $value;
}
public function equal($_instance){
return $_instance instanceof Singleton ? $this->_instance === $_instance->_instance : $this->_instance === $_instance;
}
}

With above class, using the Singleton function as well, you can even use the new keyword to obtain every time the same instance.

$b = new Singleton('B', 'my value');
echo '
', var_dump(
$b->equal(Singleton('B')->write('Hello World')) &&
$b->equal(new Singleton('B'))
), '
';

Well, at this point we have the shortest way to obtain the same behaviour, using, or not, a class.

Factory


From Wikipedia
The Factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.
The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.

Specially in PHP, a Factory pattern is useful to avoid problems with new keyword when you create an object.
For example, this is not possible:

new Class("stuff")->doStuff();

With a Factory behaviour it is natural to do something like this:

Factory('Class')->doStuff();

In those case when we need an instance once, or few times, and never more, to do some super cool computation, we could avoid variable assignment and, in some case, use a function with the same class name as proposed few days ago.
But this time, using exactly the same concept of Singleton, it is even more simple to create a general purpose Factory function:

function Factory($__CLASS__){
// webreflection.blogspot.com
static $list = array();
if(!isset($list[$__CLASS__]))
$list[$__CLASS__] = new ReflectionClass($__CLASS__);
$arguments = func_get_args();
array_shift($arguments);
return $list[$__CLASS__]->getConstructor() ? $list[$__CLASS__]->newInstanceArgs($arguments) : $list[$__CLASS__]->newInstance();
}

Some example?

class A {
public function setName($name){
$this->name = $name;
return $this;
}
}

$me = Factory('A')->setName('Andrea');
echo $me->name; // Andrea

Not every consideration I did for Singleton pattern is true for Factory one, but the structure of the function, as the possible class, is about the same.
At this point, assuming that in my implementation Factory is an extended version of the Singleton, creating more instances than one, you can have a look into the complete source of my Factory and Singleton implementation.

Why there is JavaScript in this post topic?


The reaon is simple, everything I have done with PHP, is simply replicable with JavaScript, but this time, with only 8 lines of code:

// webreflection.blogspot.com
Factory = function(__CLASS__){
for(var i = 1, length = arguments.length, args = new Array(length - 1); i < length; i++)
args[i - 1] = "arguments[" + i + "]";
return Function("return new " + __CLASS__ + "(" + args.join(",") + ")").apply(null, arguments);
};
Singleton = function(list){return function(__CLASS__){
return __CLASS__ in list ? list[__CLASS__] : list[__CLASS__] = Factory.apply(null, arguments);
}}({});

Seems to be simple, isn't it? :geek:

Has this constructor been prototyped?

This is a quick post about libraries that uses native constructor in an obtrusive way.
Using a Function prototype, that sounds like a non-sense, it is possible to know if a constructor has some property, or method, defined in its prototype.

Function.prototype.prototyped = function(){
for(var i in new this)
return true;
return false;
};


Some test example?

alert(Array.prototyped()); // false

Object.prototype.each = function(){};
alert(Array.prototyped()); // true

delete Object.prototype.each;
alert(Array.prototyped()); // false

Array.prototype.each = function(){};
alert(Array.prototyped()); // true
alert(Object.prototyped()); // false


Update
Has Kangas spotted, there is no reason to create a new instance.
We could loop directly the prototype object.
But what's up if we have injected privileged methods in the constructor?

Array = function(Array){
var prototype = Array.prototype;
return function(){
arguments = prototype.slice.call(arguments, 0);
arguments.each = function(){
prototype.forEach.apply(this, arguments);
};
return arguments;
};
}(Array);

var a = new Array(1, 2, 3);
a.each(function(value){
alert(value)
});

for(i in Array.prototype)
alert(i); // nothing

Above example is the reason I chose to create an instance ... but hey, why on heart someone should wrap a native constructor? :P

Sunday, June 8, 2008

JsonTV - JsonML concept to create TreeView components

For those that do not know JsonML, this is a little summary.
JsonML aim is to use JSON to transport layouts, instead of simple data.
Unfortunately, for this purpose the size of the code could be even bigger than regular layout, considering that with a good usage of classes, internal styles, as attributes, are often superfluous.
At the same time, there are still several problems with DOM, for its not standard nature, thanks to those browsers that do not respect W3 or generic predefined guidelines.
For these reasons, and probably others, JsonML has not been widely adopted, as is for his daddy JSON.

An alternative purpose, based on both same concept and grammar


A daily common task in web development, is menu, files and directories, or trees creation, that allow us, as users, to organize data in a better, friendly, and easy to manage, way.
Removing some intermediate step, and thinking about standard data presentation, with useful information and nothing else, it is possible to use the same JsonML grammar to create automatically a DOM based tree.
The schema could be transformed in this way:

element
= '[' name ',' attributes ',' element-list ']'
| '[' name ',' attributes ']'
| '[' name ',' element-list ']'
| '[' name ']'
| json-string
;
name
= json-string
;
attributes
= '{' attribute-list '}'
| '{' '}'
;
attribute-list
= attribute ',' attribute-list
| attribute
;
attribute
= attribute-name ':' attribute-value
;
attribute-name
= json-string
;
attribute-value
= json-string
;
element-list
= element ',' element-list
| element
;

As you can observe, the only difference is with name, instead of tag-name.
The element-list, if present, will be the nested list of informations inside a branch, while name will be the real name of that branch, or leaf, if no element-list is present inside.

The attribute-list will be a dedicated object that will contain, if present, every information we need for that leaf, or branch.
At this point, with a simple piece of code like this one, is possible to create a menu:

["root",
["demo.txt", {size:12345, date:"2008/06/07"}],
["temp",
["file1.tmp"],
["file2.tmp"],
["file3.tmp"]
],
["sound.wav", {size:567, date:"2008/05/07"}]
]

Above code will create automatically a list like this one:

  • root

    • demo.txt

    • temp

      • file1.tmp

      • file2.tmp

      • file3.tmp



    • sound.wav




Every leaf, or branch, will contain at the same time passed information, as object.
In this way, as I wrote before, we are not sending an xhtml or xml structure, but simply a schema of our menu, folder navigator, or whatever we need.

The JsonTV object


This is my JsonTV object implementation. It is truly simple to use and, if you want, raw, but it is only the core which aim is to transport, transform, create, or parse from DOM, every kind of schema that will respect showed grammar.
For example, this is a piece of code that will automatically create above tree, and will hide, or show, internal leafs, if presents, and starting from the root.

onload = function(){
var directory = JsonTV.parseArray(
["root",
["demo.txt", {size:12345, date:"2008/06/07"}],
["temp", ["file1.tmp"], ["file2.tmp"], ["file3.tmp"]],
["sound.wav", {size:456, date:"2008/05/07"}]
]
);
document.body.appendChild(
directory
).onclick = function(e){
var target = (e ? e.target : event.srcElement).parentNode,
ul = target.getElementsByTagName("ul")[0];
if(/li/i.test(target.nodeName)){
if(ul)
ul.style.display = (target.clicked = !target.clicked) ? "none" : "";
else {
var __JSON__ = [];
for(var key in target.__JSON__)
__JSON__.push(key + " = " + target.__JSON__[key]);
if(__JSON__.length)
alert(__JSON__.join("\n"));
};
};
};
directory.className = "directory";

// this is only an assertion like check
setTimeout(function(){
var clone = document.body.appendChild(JsonTV.parseArray(JsonTV.parseDOM(directory)));
if(directory.outerHTML === clone.outerHTML)
document.body.removeChild(clone);
}, 1000);
};


Simplified API


As is for JSON object, JsonTV contains two main public methods: parse, and stringify.
The first one, parse, will convert a JSON string that contains a valid schema Array, a schema Array, into a DOM based Tree.
There is an exception, if you pass a DOM based Tree to parse function, it will convert them into an Array that will respect JsonTV schema.
On the other hand, the stringify method will convert a string, a DOM based Tree, or an Array, into JsonTV string, using, if present, the official JSON.stringify method, or not standard Gecko toSource one, if there is no JSON parser.

Conclusion


This is only my first step inside JsonTV technique, but I am sure that with a good usage of CSS, and few lines of JavaScript, using or not third parts libraries, a common intermediate protocol to manage, send, save, and show tree views, could let us develop truly interesting tree based applcations, making portings from different languages more simple than ever, as it has been for JSON de-facto standard.
Stay tuned for next examples ;)

Thursday, June 5, 2008

Two simple tricks in JavaScript ( olds, but always useful )

This is a quick post about two really common pieces of code that are used daily from libraries developers and not.

Stop to use Math.floor


The first one is about usage of Math.floor. It is probably only my opinion, but it seems that Math.floor is used always to perform the same task:

var centerWidth = Math.floor((something + someelse - someother) / 2);

The point is that at the end of a Math.floor, you will often find that division by 2.
There is a truly simple way to write less, and to obtain best performances as well, it is the right side bitwise operator, that for this purpose is nearly perfect.

var centerWidth = (something + someelse - someother) >> 1;

That's it! If you compare above examples you will note that second one is about 2X faster than Math.floor.

for(var i = 0, t1 = new Date; i < 50000; i++)
Math.floor(i / 2);
t1 = new Date - t1;

for(var i = 0, t2 = new Date; i < 50000; i++)
i >> 1;
t2 = new Date - t2;

alert([t1, t2].join("\n"));


A tricky String.indexOf


Another common piece of code you can find wherever, is this one:

if(myWord.indexOf(myChar) >= 0) ...

if(-1 < myWord.indexOf(myChar)) ...

if(myWord.indexOf(myChar) !== -1) ...

There is an operator that inverts the number, adding +1, and that is perfect every time we have a function that could return 0, more than zero, or -1 where there's no match.

if(~myWord.indexOf(myChar)) ...

Above example converts every number from 0 to N into -1 to -(N+1)
Accordingly, if the result is -1, the result will be zero -(-1+1), where -0 does not make sense in JavaScript, and it is simply threaded as 0 (no limits guys :D)

The latter one is probably not known as the first one, and its execution time is about the same, but you write less, and you can recognize instantly if that method or function respect the integer -1 to +N return value.
The implicit cast when you use an if or a ternary operator, is the one that makes that check fast enough, but not faster than common way as is the first suggested trick.

P.S. these tricks could be used with many other program languages ;)

Monday, June 2, 2008

JavaScript prototype behaviour with PHP

One cool thing of JavaScript prototype model, is that you can change dynamically one or more method updating automatically every instance of that constructor.
Even if classic inheritance and OO Programmers hate this feature, it could be really useful in some case.
Another interesting thing, is that thanks to injected scope, you can share a prototype or use one of its defined methods, with every kind of instance.

PHP is (still) dynamically limited


The concept of injected scope, is absolutely extraneous to PHP developers.
Even with a massive usage of Reflection API, it is not possible to use a method of class A with another class B, even if this method contains common usable tasks for both classes.
At the same time, it is not possible to use a function as property, because it is not recognized as function, if called directly, and it cannot contain a $this referer, thanks to engine limitation.

The light comes from PECL


The official repository for PHP extensions, contains a truly interesting one that is able to modify runtime a class and every derived instance.
This extension is absolutely experimental, but right now usable in some version of PHP 5.
Its name is runkit, that with another one, called classkit, let us use PHP in a "more psychedelic way" :D

The prototype behaviour with PHP


Using a couple of technique, such an SPL interface, and runkit extension, I have been able to write and successfully execute a code like this one:

<?php

// basic class
class Demo {
public static $prototype;
}

// prototype assignment, with optional methods
Demo::$prototype = new prototype(
'Demo',
array(
'set_name' => array('$name', '$this->name = $name;'),
'get_name' => array('return $this->name;')
)
);

// a generic instance
$demo = new Demo();
$demo->set_name('Andrea Giammarchi');
echo $demo->get_name(); // Andrea Giammarchi

// add more prototypes
Demo::$prototype->set_age = array('$age', '$this->age = $age;');
Demo::$prototype->get_info = array('return $this->name." is ".$this->age." years old";');

$demo->set_age(30);
echo '
', $demo->get_info();
// Andrea Giammarchi is 30 years old

?>

In few words, I have been able to define a list of methods, to assign as prototype, to use them, and finally add more, usable with pre defined instance without problems.

Shared method emulations


What is possible to do, at this point, is to share one or more method between two classes, and without problems.
It is even possible to assign directly an entire prototype to another one, using the prototype constructor:

<?php

// same stuff of precedent example

class Constructor {

public static $prototype;

// please note that this constructor
// uses method not defined, yet :)
public function __construct($name, $age){
$this->set_name($name);
$this->set_age($age);
}

}

Constructor::$prototype = new prototype('Constructor', Demo::$prototype);

$me = new Constructor('Andrea', 30);
echo $me->get_info();
// Andrea is 30 years old

?>

Of course, another class could simply initialise its public static prototype, and then add, if necessary, only one method:

<?php

class Name {
public static $prototype;
}
Name::$prototype = new prototype('Name');
Name::$prototype->set_name = Demo::$prototype->set_name;

$me = new Name;
$me->set_name('Andrea Giammarchi');
echo $me->name;
// Andrea Giammarchi

?>


The class prototype and its limit


To successfully test above example codes, I have used my prototype class, that as I said, requires usage of SPL and runkit extension as well.

The shared method emulation, is artificial, because of runkit call that will create a new function, with same arguments and body, for each prototoype. Anyway, the usage is, in my opinion, simple as comfortable and without error possibilities, except for == or === operator that will return in every case false (so the trick is to compare the imploded version of both prototypes, if is the identical string, those are the same prototype)

if(implode('',Demo::$prototype->set_name) === implode('',Name::$prototype->set_name))
doYourStuff();


The main limit of this class is created by runkit extension, that does not let me use every kind of method name, and fails for example if I write setName instead of set_name.

In another PHP version, the 5.3.dev, it lets me use every kind of name, but crash when I try to modify one method, or to remove them using unset(ClassName::$prototype->methodName);

For these reason, you can get this class as example, but you know, right now, that with SPL and some cool PECL extension, PHP limits are truly less evident than ever.

Have fun :)

Sunday, June 1, 2008

PHP or JavaScript implicit Factory method design pattern

Update
Above technique could be used to create an implicit Singleton as well.

class Demo {
// your unbelievable stuff
}

function Demo($some, $arg){
static $instance;
return isset($instance) ? $instance : ($instance = new Demo($some, $arg));
}

Demo(1,2)->doStuff();
Demo(1,2) === Demo(1,2); // true


from Wikipedia
The factory method pattern is an object-oriented design pattern ... More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.

I have talked about JavaScript possibility different times in my prototypal inheritance documentation, and in other posts of this blog. The summary is that thanks to perfect this behaviour, that for some unknown reason someone would like to modify in JS2, making them ambiguous when you are using a constructor as a function and not, for example, as private method, we can create intelligent constructors that does not require the usage of new keyword - in a Pythonic way:

// JavaScript
function Person(name, age){
if(this instanceof Person){
this.name = name;
this.age = age;
} else
return new Person(name, age);
};
Person.prototype.getInfo = function(){
return this.name + " is " + this.age + " years old";
};

// Example
alert(
Person("Andrea", 30).getInfo() // Andrea is 30 years old
);

var a = Person("Luca", 25),
b = Person("Fabio", 31);

The main advantage, using this technique, is that we write less code and we are able to concatenate every public method, allowing us to do different stuff in few lines.

alert(
Person(name, age).transFormToEmployee(company).getInfo()
);


The new keyword


We could use simply constructor when we would like to create an instance and use then directly a public method.

var time = (new Date).getTime();

// same as
var time = new Date().getTime();

// different of
var time = new Date.getTime(); // Date.getTime is not a constructor !!

Above examples show JavaScript new keyword nature, and its priority when we use brackets around, or at the of the constructor - passing, or not, one or more arguments. With implicit factory method purpose, we could simply do stuff like this one:

// just a basic (and wrong) example of implicit factory implementation
Date = function(Date){
return function(){
return this instanceof Date ? this : new Date;
};
}(Date);

var time = Date().getTime();

To be honest, with native or defined constructors, we should put more effort to implement my proposed technique, but the aim of this post is to show how could be possibile to do the same, with PHP.

PHP implicit Factory method


I suppose that if you are an Object Oriented PHP Programmer, you have tried, at least once, to do something like this and without success:

echo new Person("Me", 30)->getInfo();
echo (new Person("Me", 30))->getInfo();

Since in PHP both usage of brackets and syntax are different, the "only" way we have to concatenate public methods is to create a manual factory one:

class Person {

// ... our stuff ...

static public function create($name, $age){
return new Person($name, $age);
}
}

echo Person::create($name, $age)->getInfo();

Above example is a very common one in many OO frameworks or libraries.

Ambiguity


You probably don't know that thanks to some intrinsic PHP language ambiguity, it is possible to create a function with the same name of a class, as is, for example, for constants, but this time without future features problems.

// PHP
class Person {
function Person($name, $age){
$this->name = $name;
$this->age = $age;
}
function getInfo(){
return "{$this->name} is {$this->age} years old";
}
}

// factory method!!!
function Person($name, $age){
return new Person($name, $age);
}

// Example
echo Person("Andrea", 30)->getInfo(); // Andrea is 30 years old
?>

The PHP interpreter is able to recognize if we are calling the class or the function, simply looking at new keyword.
If we are using them, it will be obviously an instance creation, while if we are not using them, it will be obviously a function call.
The last case is if we do not use brackets, and then it will be the defined constant, if any, or, in a better future, the static public __toString method, if any again.

The __autofactory function


Since this way to code and use classes and functions could be truly interesting, and since we could have one to thousands of classes, it is natural to think how to automatically implement this kind of feature in our project.
The answer is a function, called __autofactory, that will be able to create a file to include, or require, that will contain every defined class as function, using best practices to speed up implicit factory method usage.
The only thing to write before logic code execution, is this piece of code:

// ... application classes inclusions

// before code logic
require '__autofactory.php';
!file_exists($fileName = 'factory.function.php') && __autofactory($fileName);

The first parameter will be the name of the file that will contain informations, while the second one will specify, if present and with a false evaluable data, if function should require them or not.

At this point, you have basis and / or code to use this particular feature for every kind of purpose.