My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, July 16, 2008

JavaScript Relator Object, aka unobtrusive informations

Have you never though about add, modify, or remove a generic information from a variable, and without changing variable itself?
This is all about what my last simple creation does.



Relator Object Concept


The main purpose for this object is to associate every kind of information, value, or function, into a generic variable, whatever it is, and without modifying its native state.
To obtain this result, I have used a 1:1 relationship between a stack that will contain every stored variable, and another one that will contain related objects.

Stack = [1, 2, 3];
RelatedObject = [{}, {}, {}];

// add a property
RelatedObject[Stack.indexOf(2)].description = "Number 2";

// remove a property
Stack.splice(0, 1);
RelatedObject.splice(0, 1);

// situation
Stack = [2, 3];
RelatedObject = [{description:"Number 2"}, {}];

Using above strategy we obtain 2 benefits:

  1. The Stack does not cause memory leaks

  2. both Stack and RelatedObject are alway as small, and fast, as possible





Related Object Code



var Relator = function(Array, Object){
// (c) Andrea Giammarchi - Mit Style License
if(!Array.indexOf)
Array.indexOf = function(value){
for(var i = 0, length = Array.length; i < length; i++)
if(Array[i] === value)
return i;
return -1
};
return {
get:function(value){
return Object[Array.indexOf(value)]
},
set:function(value){
var i = Array.indexOf(value);
return ~i ? Object[i] : Object[Array.push(value) - 1] = {}
},
del:function(value){
var i = Array.indexOf(value);
if(~i){
Array.splice(i, 1);
Object.splice(i, 1);
};
return this
}
}
}([], []);

I hope, and I suppose, the 3 methods API talks by itself.
set is used to create a relation, if this does not exists, returning associated object.
get is used only to get a relation or undefined, if this does not exist.
Finally, del, is used to delete the relation, reducing the Array size, and deleting related Object.



Some Example


Try to imagine that we are using a library, but we would be able to add any sort of info about them, or implement something for our purpose.

var jQueryMore = Relator.set(jQuery);
jQueryMore.details = "jQuery library";
jQueryMore.isCompatible = function(){
return window.$ === jQuery;
};

// in every other piece of code ...
if(Relator.get(jQuery).isCompatible())
alert("I am using the " + Relator.get(jQuery).details);
// I am using the jQuery library




Relator Performances


IE a part, since it still does not implement natively the old indexOf Array method, performance to set, access, modify, or delete related informations, are probably the best possible, closes to zero value.
We can test by ourself using 10000 stored relations, and accessing to the last one.

for(var i = 0; i < 10000; i++)
Relator.set("number " + i).description = "The " + i + " number";

time = new Date;
description = Relator.get("number " + 9999).description;
time = new Date - time;
alert([description, time]);




Conclusion


The Relator object is based on our own variables, and it is not a container, a register, or a IOC emulator, at all.
At the same time, to be able to relate an object with a generic variable (undefined included, as example), it needs to store them in the Stack.
This could be a problem for memory leaks, but only if we forget to use the del method, to remove the assigned, and protected, relation between our global scope whatever, and the internal object dedicated relation.
Applications? In my mind, this object could make a lot of stuff simpler than ever, specially in those case where we would like, for example, monitor variables, singleton or global instances, during our script life :)

Saturday, July 12, 2008

An alternative JavaScript development pattern

A common pattern to develop JavaScript libraries is to use different behaviours inside methods, and based on browser, or browser plus its version.
For about 80% of cases, these behaviours are Internet Explorer dedicated.
This approach is good enough, otherwise we could not have a wide variety of libraries to choose, but is this way to develop libraries the best one?

These are some pro concepts:

  • libraries could be usually merged into a single file, so we can add only one script tag, and for every browser

  • libraries maintenance or improvements are focused into one, or more, constructor, function, or method



The expected result is, usually, a method that is capable to understand which browser is running them, and what to do for that specific case.

// common libraries development pattern
function myGorgeusLib(){};
myGorgeusLib.prototype.sayHello = function(){
if(self.attachEvent)
attachEvent("onload", function(){alert("Hello")});
else if(self.addEventListener)
addEventListener("load", function(e){alert("Hello")}, false);
else
onload = function(onload){return onload ?
function(){onload();alert("Hello")} :
function(){alert("Hello")}
}(self.onload);
};

new myGorgeusLib().sayHello();

Is above code clear enough? If a browser implements attachEvent, use them, otherwise if it implements addEventListener, use them, otherwise use manual onload implementation.

If we would like to modify, for some reason, that method, there is only one "place" to do it, the method itself.
At the same time, every time we would like to use that method, the browser has to check 1 or 2 times which case is suited for its engine.

This concept introduces these side effects:

  • every method size is generally increased for every browser, and often only to make some task IE compatible

  • every method speed execution, is generally increased, because of useless, or necessary, checks to perform each time the method is called

  • every change inside every method, could cause side effects for other browsers, so we have to fix 3 to 4 times instead of once, because of possible problems

  • every changed method should be tested into every library supported browser, even if it worked perfectly with every one, IE a part



Lazy, or direct, method assignment


Some library implements lazy prototype assignment, so that method will be the best one, only after the first time we will use them.

// lazy method assignment
function myGorgeusLib(){};
myGorgeusLib.prototype.sayHello = function(){
myGorgeusLib.prototype.sayHello =
self.attachEvent ? function(){
attachEvent("onload", function(){alert("Hello")});
}:(
self.addEventListener ? function(){
addEventListener("load", function(e){alert("Hello")}, false);
}:
function(){
onload = function(onload){return onload ?
function(){onload();alert("Hello")} :
function(){alert("Hello")}
}(self.onload);
}
);
this.sayHello();
};

new myGorgeusLib().sayHello();

Since we could perform that kind of check directly during prototype assignment, in this case, above pattern, is completely useless.
On the other hand, doing lazy or direct dedicated assignment, we are using a better approach because:

  • method is specific for this, or that, browser, so its execution speed will be the fastest possible

  • if we need to fix that method, we can focus only into specific browser version. Accordingly, we do not need to test with every supported browser, every change we made, but only with one, or more, specific version


Code minifier maniacs, could think that in this way, and for each method that requires that strategy, the final size of the library could increase about 30%, and this is, basically, true.
So, at this point, we have the best method ever to perform that specific task, but not the best size. How could we solve this last problem?

An alternative library development pattern


Before I will talk about my proposal, we should focus on a simple, as useful, thing about libraries: modularity
What we do like about this, or that, library, is the possibility to include only what we need, to obtain the final result with smallest possible footprint.
In other words, we chose exactly what we need, and we load or use only them, without useless piece of code that could only increase our page size, with or without cache help.
A lot of libraries use this concept runtime, like Dojo, or directly during library generation, like MooTools.
This way to develop, mantain, and use libraries, is loads of benefits for both developers, and users.
At the same time, and as far as I know, nobody though to port this development pattern, to create each library "portion" a part.
This is an example of what I am talking about:

// alternative library development pattern
function myGorgeusLib(){};
myGorgeusLib.prototype.sayHello = function(){
addEventListener("load", function(e){alert("Hello")}, false);
};

// IE dedicated changes, separated file
myGorgeusLib.prototype.sayHello = function(){
attachEvent("onload", function(){alert("Hello")});
};

// if we would like to support really old browsers too, in a separated file
myGorgeusLib.prototype.sayHello = function(){
onload = function(onload){return onload ?
function(){onload();alert("Hello")} :
function(){alert("Hello")}
}(self.onload);
};


This is a benefits summary, about this proposal:

  • smallest library size ever, thanks to common standard methods used by the library itself (a sort of FireFox, Opera, and Safari dedicated version)

  • modular methods development, with separed files dedicated for one, or more, browser version (IE6, IE7, IE8), thanks to conditional IE standard HTML comments: <!--[if IE 7]><script type="text/javascript" src="library.IE7.js"></script><![endif]-->

  • "future proof", when IE will implement standard DOM or Events methods, and behaviours, we can reduce IE dedicated file size

  • single debug, modular updates. We changes only one, or more, file, instead of recompile, regenerate, redistribute, the entire library file

  • intranet friendly, update only library version for dedicated environment, if it uses only a specific browser


So why shoulld we use JavaScript to define library behaviour, instead of browser itself?
Anyway, this pattern completely brakes practices about script tags in a generic (x)?HTML page. But, at the same time, could be the key to solve a wide number of problems, starting from modern devices with possible memory limits for JavaScript files, up to library execution speed, the best possible, and maintenance, focused in a single browser, or a single browser version.
The best implementation could be a Dojo "progressive library load" style, where the core automatically knows which file should be loaded, depending on browser, or its version.
Finally, these are side effects about this pattern:

  • final and complete library size will be the biggest possible one, but there shouldn't be a case where a browser download every file, redefining N times one or more methods

  • more effort to develop an entire library using this way, if there are a lot of methods that are not compatible with every browser

  • probably something else, that I am not thinking about



Now, after this explanation, would you like to write your impressions? Cheers :)

Thursday, July 10, 2008

He wrote: I'd like to know your opinion about JS2 ...

... and here I am.

My opinion about ECMAScript 4 is not that simple to explain.

I would like to have a language, whatever it is, that is powerful, truly natively cross browser, and widely adopted from every kind of device.

It seems I am talking about ActionScript, since Flash Player respects, aproximatly 90%, my desires, but I am not.

I "come" from Macromedia world, as a Certified ActionScript 2.0 Developer (no design guys, only pure AS2 OOP), and I have used, for years, Flash as production environment.

Looking at the little "JS2 monster" they are creating, I could smile, thinking about problems I had for those years with an environment that would like to be compatible with both old and new code, loads of unresolved bugs, and never perfectly cross browser ... we just have them, it is JavaScript, with its numerous implementations.

At the same time, I would love to see JavaScript 2 power, in a bytecode based VM, but what I do not want, is a partial implementation of this new language, as I do not hope in a JS3 project at all ( Macromedia style, every maximum 1 or 2 years a new language, so that nobody was really skilled and nobody knew perfectly the environment and language features itself ... welcome Adobe, and its hybrid Flash player that could do more, but only with Flex ... but it is only about marketing, isn't it? )

After 10 years or more, we are still "discovering" patterns and practices for a language born so far ( today, as example, another post about prototypal inheritance, using bad practices to perform simple, and logical, tasks - this is the state of general JS knowledge, 2008 )

Furthermore, as far as I know, Microsoft invested a lot of effort for its SilverLight pearl, a technology that, after years, is not that far from what Adobe, and Macromedia before, has done during these web evolution days and for long time.

I think, and it is only my humble opinion, that MS will never implement natively in its browser an open source VM, which purpose is to make Web more standard, at least for development, and more powerful for everyone:

You want more for your browser? You want SilverLight!


We would like to have canvas ( fast graphic? SilverLight ), standard behaviors, libraries which size could be 1/3, removing every single line IE dedicated ( fast and easy development? SilverLight ) ... but we still have attachEvent, old Array methods, and we know what else.

So, definitively, if JS2 will be the key to write once and run everywhere, without 3rd parts plug ins, without strict usage licenses, with more speed, more power, and capable to run in every device, I cannot wait that day ... but I am pretty much sure, that it is not close as I hope.

What about solving problems with ECMAScript 3rd edition, fixing everything, and in every browser? A dream, or better, an utopia!

So let's start to learn, to develop, and to fix, a new language :geek:

Thursday, July 03, 2008

scary eval to create the most safe environment ever

Are you worried about Array redefinition?
Are you worried about eval function redefinition?
Are you worried about whatever you want redefinition?
STOP
With the incredible eval feature "discovered" few days ago, it possible to create the most safe environment ever for every kind of purpose, starting from JSON evaluation, arriving to total protected native constructors.


const safeEnvironment = function(A, B, D, F, N, O, R, S){
const Array = A,
Boolean = B,
Date = D,
Function= F,
Number = N,
Object = O,
RegExp = R,
String = S,
eval = function(String){
return self.eval("(" + String + ")");
};
return new function(){};
}(
Array,
Boolean,
Date,
Function,
Number,
Object,
RegExp,
String
);


With above piece of code you can evaluate every kind of script without to be worried about common XSS or evaluation problems.


eval("Array=function(){}; alert(Array);", safeEnvironment);
/*
function Array(){
[native code]
}
*/


Seems to be hilarious, isn't it? The most scary Gecko function let us redefine entirely an environment, using constants to create immutable values that will be present in the virtual sandboxed scope.

So, the paradox, is that with Gecko eval, we could create the perfect safe environment, that could be used for every purpose, starting from the NoScript stuff.

Please, help me to convince Mozilla staff that second argument is not dangerous and could make our code execution safer than ever, thank you!

Wednesday, July 02, 2008

SCARY EVAL ... and the "futuristic" solution

Planet Earth, Year 2000

eval("document." + myformName + "." + myInputName + ".value");



Satellite Moon, Year 2004

eval is evil, nobody should use them, "except for json evaluation"



Planet Earth 2.0, Year 2008
OMG somebody could penetrate my closures!!!


Web Reflection, few days later
First of all, it was in the MDC, so if everbody is surprised, it is because we did not read that page, or simply we did not try that code (please correct that page, the second argument is everything but not the same of with statement).

Secondly, please, DO NOT CHANGE THAT FEATURE!!!
What I mean is that JavaScript is an amazing language, where everything could be changed, thanks to its intrinsically dynamic nature.

If we are worried about this fake news:

  • we should worry, before, about XSS in our site (after SQL injections)

  • if we are sure about missed XSS possibility, we should be worried about external libraries

  • if we are sure about third parts libraries, we should be worried about JSON

  • if we are sure about external libraries and JSON interactions ... why on heart should we be worried about this historic feature?



The feature is present in Gecko, but hey, Gecko implements constants!!!
Another thing I could not understand, is why somebody opened a bug for a feature that could be AMAZING if used for our own purpose.

Code and closure introspections, protected method implementation, whatever I cannot imagine right now.

On the other hand, it is extremely simple to solve the problem using a basic constant declaration

// webreflection "from the space"
try{eval("const $eval=function(eval){return function($eval){return eval($eval)}}(eval)")}catch($){$eval=eval};


Now try to delete the constant, try to do whatever you want in FireFox, and if it will be possible to change that $eval behaviour with Gecko browser, that will be the only bug you should really fix.

With Best Regards,
your bloody evil propagator ( booh! )



Update
Since I am writing in the bug page, I think my example could be interesting to understand what we are going to loose when this feature will disappear:

// sandbox: redefined environment
var myEnvironMent = {
eval:function(script){
return eval(script);
},
alert:function(String){
(document.body || document.documentElement)
.appendChild(document.createTextNode(String));
}
};

// evaluate a script from a string or a textarea
eval("alert('Hello World')", myEnvironMent);

/* you cannot do this with a with statement
with(myEnvironMent)
eval("alert('Hello World')");
*/



// privileged protected methods in prototype
Protected = function(){
function _showMessage(message){
alert(this.name.concat(" say ", message));
}
return function(name){
this.name = name;
};
}();
Protected.prototype._ = function(method){
return eval("_" + method, this)
.apply(this, Array.prototype.slice.call(arguments, 1));
};

var p = new Protected("Andrea");
p._("showMessage", "Hello World");

These are only two quick examples, and I wrote them in 1 minute.
Now try to imagine what could be possible to do having such control over closures!

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 08, 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 05, 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 02, 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 01, 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.

Saturday, May 24, 2008

More standard Stack, and more slim ArrayObject

I have just updated both Stack and ArrayObject constructors.

The Stack improvement is About concat method, now truly standard, accepting arguments that are not instance of Stack or Array.

var s = new Stack(1, 2, 3);
alert(s.concat([4, 5], 6)); // 1,2,3,4,5,6


Since this method uses defined slice one, there is no more reason to redefine concat method in inherited prototypes. That is why ArrayObject does not need anymore concat method, for a total of 4 fast redefined methods, plus inherited concat.

ArrayObject is now the fastest extended Array constructor that returns instances of the same constructor, ArrayObject.

ArrayObject is, at the same time, the base to create every other kind of cool library, using native Array methods power.

Enjoy!

Thursday, May 22, 2008

[OT] Does Zend rely in its own program language?

During an interesting meeting at work, me and my colleagues talked, for some reason, about Zend, and its weird market strategy.

What I mean, is that articles like this one, are daily present in our mind (we, as certified PHP developers :D)

At the same time, today I though about one simple thing:

  • Which program language is the diamond of MS? C#

  • Which program language does MS use to create applications? C#

  • Is MS IDE writen in C#, to develop in C#? Almost

  • Which program language is the diamond of Sun Microsystem? Java

  • Which program language does Sun use to create applications? Java

  • Is Eclipse IDE written in Java, to develop in Java? Almost



Same loop could be applied for Python, Ruby, D, Ocaml ... others, now stop one second ...

  • Which program language is the diamond of Zend? PHP

  • Which program language does Zend use to create applications? Java

  • Is Zend IDE written in PHP (GTK), to develop in PHP? NO



I know that phpgtk is a project out of the box, but it seems that Zend does not rely in its self proposed program language, or in its amazing extensions, as php gtk is.


  • Is it because PHP is not stable, scalable, powerful, as Java is? (don't you really know the answer?)

  • Is it because PHP is known as web purpose language, and it has not official support for desktop development? Maybe ... or maybe first point is more credible ...



I do like PHP, and what it offers daily for web development, but problems, bugs, simultaneous developed versions, let me think that probably we are using a program language, while its "official sponsor" does not like them that much ... but it's only my humble opinion, and I am using PHP since 1999 - am I an idiot?

Stack and ArrayObject - How to create an advanced subclassed Array constructor

Another problem left to solve is that after subclassing an Array one would like the return types of Array.prototype methods to be of the subclass type instead of its superclass type Array.

This comment is, basically, a summary of the reason I created the ArrayObject constructor.

Today, I have totally rewrote that constructor, using a Stack instance as prototype.

The Stack constructor aim is to subclass the Array one in the most compatible, and light, way.

For this reason, I have not changed native Array behaviours, those that return an Array, for example, instead of a Stack instance (concat, filter, map, slice).

But the good thing of Stack, is that now we can create our subclassed Array constructor, without affecting the native Array object, and adding, modifying, or removing, whatever we want.

For example, to solve the problem described on top of this post, I have simply modified inherited Stack methods, returning an instance of ArrayObject, every time we use, for example, a concat.

var a = new ArrayObject(1,2,3),
b = new ArrayObject(7,8,9),
c = a.concat([4,5,6], b);
alert(c); // 1,2,3,4,5,6,7,8,9
alert(c instanceof ArrayObject); // true

The same behaviour is obtained using slice, map, or filter, so we have our constructor, with our prototype, loads of possibilities.

The valueOf revenge


In ArrayObject, I have changed valueOf behaviour. This method returns basically the same information of toString, but it is used internally in a lot of cases.
One of them, is when you compare, sum, multiply, divide, whatever two variables.

// how to know if an ArrayObject has more elements than other one
var a = new ArrayObject(1,2,3),
b = new ArrayObject(4);
alert(a > b); // false

Above example calls in an implicit way the valueOf prototype methods.
Since latter one returns the length of the ArrayObject, and since b is an ArrayObject with length of 4, the a variable, with only 3 elements, will fail that kind of check.
Another interesting example that could allow us to write less code is this kind of check to know if an ArrayObject has some element:

var a = new ArrayObject(),
b = new ArrayObject(1,2,3);
if(-a)
alert("a has some element");
if(-b)
alert(b); // 1,2,3

Above example shows how to use in a quick and dirty way the valueOf behaviour with an ArrayObject instance. It is the same of:

if(a.length)
alert("a has some element");
if(b.length)
alert(b); // 1,2,3


The "to" prototype and the public static create


In the old ArrayObject version, I used a to prototype to convert a variable into a different one, using a constructor.
The main purpose of the Stack constructor, is to avoid Array.prototype methods assignment, as should be for every other native constructor to avoid problems between libraries.
In this version, the to prototype is only for ArrayObject:

var a = new ArrayObject(4,5,6),
b = [1,2,3].concat(a.to(Array));

In this way we could convert an ArrayObject in every other Array like compatible instance, such Array, or Stack itself.

To invert the conversion, we could use the factory pattern via create.

var a = [1,2,3],
b = ArrayObject.create(a).reverse();
alert(b instanceof ArrayObject); // true


I am working to fix last little problems with my code, but I think both Stack and ArrayObject could be used witout problems, and starting right now ;)

Tuesday, May 20, 2008

Habemus Array ... unlocked length in IE8, subclassed Array for every browser

History


I do not know how many time, during these years, JavaScript Ninjas tried to subclass the native Array to create libraries over its powerful methods without losing performances. I have finally discovered the way to remove locked length from Internet Explorer 8, and to solve problems with every other browser.

We tried to inherit Array instead of Object


This is where my last trip started, simply looking at arguments behaviour. It was there, since 2000 when I started to code in JavaScript, and it was so simple that probably few developers thought about them!

var o = {
length:0,
push:Array.prototype.push,
toString:Array.prototype.join
};

o.push(1,2,3);
alert(o); // 1,2,3

arguments, in JavaScript, is an instanceof Object, and not an Array, as is in ActionScript since version 1.0
What we have done all this time, is to use Array.prototype methods injecting a basic object, with a simple length parameter, inside.
If an object with a length value can be used as an Array, why on heart above code should not work?

We all love prototypal inheritance, we all want an instanceof Array


If you try to inherit directly an array as prototype, Internet Explorer will fix every instance length property, destroying possibility to use simple for loop over generated values.

function MyArray(){};
MyArray.prototype = [];

var a = new MyArray;
a.push(1,2,3);
alert(a.length); // 0 with every Internet Explorer

Problems are much more than a fixed length, as I wrote many months ago when I presented my ArrayObject.
On the other hand, this kind problem has been fixed for Internet Explorer 8, and 7 emulation.
Yes, finally I did it!

/**
* Choose a name for subclassed Array
*/
Stack = (function(){ // (C) Andrea Giammarchi - Mit Style License

/**
* Your personal Array constructor
*/
function Stack(length){
if(arguments.length === 1 && typeof length === "number")
this.length = -1 < length && length === length << 1 >> 1 ? length : this.push(length);
else if(arguments.length)
this.push.apply(this, arguments);
};

// Solution 1:
// Declaration of generic function
// with an array as prototype
function Array(){};
Array.prototype = [];

// Solution 2:
// use the prototype chain to inherit
// Array constructor and its native prototype
Stack.prototype = new Array;

// Solution 3:
// overwrite inherited length with zero value
Stack.prototype.length = 0;

// Solution 4:
// redeclare toString method in this way
// to let JScript core feel better
Stack.prototype.toString = function(){
return this.slice(0).toString();
};

/**
* Return and assign subclassed Array
*/
Stack.prototype.constructor = Stack;
return Stack;

})();

Above code is the basis to create an alternative Array constructor that will be able to work as expected with every browser plus IE8, without length problems.
If you try to remove a single comma from some Solution, it will never work.
If you directly assign an array to the prototype, length will be fixed.
If you remove toString prototype, FireFox and others will not work as expected.

The definitive workaround for every browser


Since first part of this post could be used in every browser, starting from IE 5.5, these old browser can simply use a constructor with a prototype full of native methods, but without instanceof Array behavior.
At the same time, every other cool browser (Safari, Firefox, Opera) could use above code to have the same behavior of IE8.

This is the full cross browser Stack constructor

While this is an improvement over basic JS 1.5 Array, to have JS 1.7 methods too, natives with updated browsers, emulated in a fast standard way with every other.
Stack Extended JS 1.7 Subclassed Array

The last problem to solve, the concat method


concat, is as simple as truly bastard prototype!
There is no way to use native concat method, even with prototypal chain inherited native Array instances.
This is why I have normalized that method, in a Stack self compatible way.
On the other hand, you cannot send a Stack instance as concat parameter, but you can always use native slice method, fast as native one is.

Best performances ever


Yes, using native, incore, prototypes, makes your code execution faster.
This compatibility + benchmark page, can tell you more about this Stack implementation than me, specially with IE8, Safari, and Opera, where performances are neary the same of a generic Array.

FireFox is probably the one that has more problems to manage native code with dynamic constructors, but hey, I am talking about Firefox beta 3, while probably RC1 or nex release will be fast as Safari, or Opera, are.

What to do with Stack?


Libraries, libraries, and libraries, finally with core performaces, the possibility to truly extend the Array, removing every fake iframe, popup, whathever you have used during these days.

Have fun with Stack, and see you soon for some other cool example with them :geek:

Sunday, April 27, 2008

Phomet changes name, so welcome Phico project

This is both an update and a news about my little Phomet project.

I am sorry because I have not found time to write better examples or to explain possibilities as well, but I am sure you would like to know that now the project is called Phico (click there to download them)

See you as soon as possible to talk again about Phico :geek:

Monday, April 21, 2008

Phomet - PHP Comet tiny library

Comet is a particular technique to interact asyncronously with the client.
Instead of perform a lot of calls using Ajax (polling) the server is able to send to client, whenever it wants, a generic response.

Unfortunately in the PHP world there's no simple way to implement this kind of technique and I'll write more posts to explain better how to implement this library and what is generally possible to do, or not possible yet, with Comet idea inside a dedicated PHP environment.

At the moment, the only thing you can do is read documentation inside JavaScript and PHP files (truly few lines) and test the first basic example, a server side clock in less than 30 lines of mixed code.

As last information, Phomet comes with all necessary to be optimized on client, and its final result is about 1.57Kb on client, and ridiculously 4.52 Kb on server, comments included :)

Here is the download, unpack them into your localhost, and go into phomet folder to view the first demo.

Compatibility? I've tested them with IE6, 7, 8, Opera 9, FireFox 1.5, 2, 3, Safari 3 windows but I am sure there are other browsers compatible.

I am waiting for your suggestions, bugs, opinions, whatever :D

Cheers, and please stay tuned for next Comet appointments :geek:

Monday, April 14, 2008

Script Type PHP :)

Update 2008/03/15
I have removed preg_replace and added DOM classes to parse and manage, in a better way, script nodes that contain php code.
Everything inside a simple PHP 5 compatible class.
Finally, please remember that this is a layer between <?php ?> and JavaScript, and only an experiment ;)

Here you can read another example, where difference between server, output, and client, should be more clear than precedent one.

<?php require 'PHPScriptHandler.php'; ?>
<html>
<head>
<title>Hello PHP World</title>
<script type="text/php" author="andr3a">

// here we are between the server and output, known as client
$hello = ucwords('hello php world');

// imagine that we would like to use a variable
// defined somewhere in the server
global $something;

// we could even include or require php files
// perform database operations and everything else
</script>
<script type="text/javascript">
onload = function(){
// here we are in the client, on window load event
alert($hello);
alert($something);
};
</script>
</head>
<body>
<?php
// here we are in the server side
// we could do what we do every day without problems
$something = '<div>Hello Body</div>';
echo $something;
?>
</body>
</html>


-------------------------------

This is a little experiment to emulate script tag with php.
The final result will be something like this one:

<html>
<head>
<title>Hello PHP World</title>
<script type="text/php">

// string
$hello = ucwords('hello php world');

// object
$o = new stdClass;
$o->test = 'hello again';

</script>
<script type="text/javascript">
onload = function(){
alert($hello);
alert($o.test);
};
</script>
</head>
<body>
</body>
</html>

How can it be possible?

<?php // 5 - PHP Script Handler Experiment - by Andrea Giammarchi
function php_script_handler($output){return stripos($output, 'type="text/php"') ? preg_replace_callback('#(?i)<script[[:space:]]+type="text/php"(.*?)>([^\a]+?)</script>#', 'php_script_parser', $output) : $output;}
function php_script_parser(){eval(end(func_get_arg(0)));return '<script type="text/javascript"'.next(func_get_arg(0)).'>'.PHP_EOL.php_script_vars(get_defined_vars()).PHP_EOL.'</script>';}
function php_script_vars($vars){foreach($vars as $key => $value)$vars[$key] = '$'.$key.'='.json_encode($value).';';return implode(PHP_EOL, $vars);}
ob_start('php_script_handler');
?>

Of course, we need to include this file before we write a single character in the layout (spaces included), so basically to obtain the expected result, just save above code in a file called, for example, php_script_handler.php, and put them before the layout

<?php require 'php_script_handler.php'; ?>
<html>
<head>
<title>Hello PHP World</title>
.... other stuff ....


The evil eval? Yes, absolutely ... but first of all, this is only a simple experiment, secondly, the page will not be sent before evaluation, so there's no way from the client side to inject malicious code.

The main problem is true interoperability between these two languages, JavaScript, and PHP, but did I say that this is only an experiment? :P

Friday, April 11, 2008

Io programming language List for JavaScript

Io is a small, prototype-based programming language. The ideas in Io are mostly inspired by Smalltalk (all values are objects, all messages are dynamic), Self (prototype-based), NewtonScript (differential inheritance), Act1 (actors and futures for concurrency), LISP (code is a runtime inspectable/modifiable tree) and Lua (small, embeddable).

This programming language is really interesting, starting from syntax, throw the entire guide.

One of its primitive type is called List, and this is a summary of this type:
A List is an array of references and supports all the standard array manipulation and enumeration methods.

It seems that List is all we need when we think about an Array of elements ... so why couldn't we have something similar in JavaScript?

// Io programming language List example
// followed by my JavaScript List implementation
a := List clone
a = List.clone()

a := list(33, "a")
a = list(33, "a")

a append("b")
a.append("b")
==> list(33, "a", "b")

a size
a.size
==> 3

a at(1)
a.at(1)
==> "a"

a atPut(2, "foo")
a.atPut(2, "foo")
==> list(33, "a", "foo", "b")

a atPut(6, "Fred")
a.atPut(6, "Fred")
==> Exception: index out of bounds

a remove("foo")
a.remove("foo")
==> list(33, "a", "b")

a atPut(2, "foo")
a.atPut(2, "foo")
==> list(33, "a", "foo", "56")

a := list(65, 21, 122)
a = list(65, 21, 122);

a foreach(i, v, write(i, ":", v, ", "))
a.foreach(function(i, v){alert(i + ":" + v + ", ")})
==> 0:65, 1:21, 2:122,

a foreach(v, v println)
a.foreach(function(v){document.writeln(v)})
==> 65
21
122

numbers := list(1, 2, 3, 4, 5, 6)
numbers = list(1, 2, 3, 4, 5, 6)

numbers select(x, x isOdd)
numbers.select(function isOdd(x){return !!(x%2)})
==> list(1, 3, 5)

numbers select(i, x, x isOdd)
numbers.select(function isOdd(i, x){return !!(x%2)})
==> list(1, 3, 5)

numbers map(x, x*2)
numbers.map(function(x){return x*2})
==> list(2, 4, 6, 8, 10, 12)

numbers map(i, x, x+i)
numbers.map(function(i, x){return x+i})
==> list(1, 3, 5, 7, 9, 11)

The map and select methods return new lists. To do the same operations in-place, you can use selectInPlace() and mapInPlace() methods.

and my implementation has mapInPlace and selectInPlace as well :)

Am I forgetting something? ... of course, the source!

P.S. because of nature of List, you can do stuff like this one:

list(1,2,3).append(4).remove(2).size;
// 3

an so on ;)

Wednesday, April 09, 2008

S.O.S. JavaScript - How to recover your stuff !!!

In this Ajax Web era there are a lot of sites that use JavaScript to perform simple or complex stuff.

Sometime, one of these site could be "not so well" programmed, specially during client-server interactions.

For example, it happens few days ago that while I was trying to post a message to another "friend", an error occurred during this operation.

The result was a beautiful fake popup with returned server error information and only a button to close them ... and I wondered what about my content? Can I try again to send them?

The answer was NO, because the SEND button has been disabled, and the worst thing is that the textarea with my message was disabled as well.

I wasn't able to get my message content again because of some client/server error and some bad logic in the client side. What could we do in these cases?

Reading the source? ... uhm, content wasn't there ...
Using firebug? Maybe, but content could not be there as well ...

Press F5 and reload the page? ... ok, but why should we loose our content in this way? What I mean, I wasted my time to write that message and why on heart should I spend twice ... ok, ok, here I come with these "stupid" links:


If you bookmark these links, dragging them in your Browser Bookmarks area, you will be able in 90% of cases to enable again the blocked page.

Basically, I created the first one (runtime and in few seconds), Enable Area, to get my content that was inside the disabled textarea, to refresh the page and try the entire operation without loosing whatever I wrote before.

The simple used code is this one:

(function(A,G){A=document.getElementsByTagName(A);G=A.length;while(G--)A[G].disabled=!A})("textarea")

and the difference between those links is only in the sent parameter, the first is the string textarea, the second is the string input, and finally the third one is the string button.

These links, and this code, are compatible with every browser that supports javascript uris (so, basically, every recent browser where recent means since some year ago ...)

Finally, in this way we use JavaScript to help us with pages that have problems with JavaScript, sounds weird? :D