pierrespring.com

geek, punk, pussy …

Discussion 3: phpBB

Pierre Spring Podcast

This is a discussion about phpBB I had with Nils Adermann. Nils is the Lead Developer of phpBB and talks about the history and future of the bulletin board. It was recorded at the Symfony Live 2011 conference.

March 4th, 2011

Two Talks at Symfony Live 2011

I am thrilled to announce that I’ll be talking at the Paris edition of the Symfony Live Conference in a couple of weeks!

I have been introduced to symfony 1.4 a bit over a year ago and it was a revelation. I was about to jump over to Python in order to be able to use Django for my private projects when Jordi and Lukas basically force fed me symfony. It’s ease of use and the amazing documentation that came along made me forget all about Django. I spent several evenings going through the Jobeet tutorial and I was ready to bootstrap my first webapp in just a few hours.

Due to its amazing documentation, we got an entire team ready for productive work in under 2 days at Liip.

Symfony2

The next big thing will be Symfony2. Symfony2 is a complete rewrite of the framework that will give your next project a strong foundation. Dependency injection makes it completely testable and modular, it makes use of namespaces and supports http-cache and ESI. And there is much more!

Symfony2 is probably the one and only state of the art PHP framework you should consider these days. And if you want to learn more about it, join us at the Symfony Live 2011 in Paris.

I will be talking about frontend optimization and PHP security in Paris along with 29 of the most interesting people in the PHP world.

Don’t you think you should join us?

February 21st, 2011

TechZing Compilation – Bootstrapping

Justin Vincent from TechZing made a compilation of Podcasts around Bootstrapping a Web App Business.

I wanted to download all of these episodes to listen to them on my iPod later. This is why I created an RSS feed of the compilation to use with iTunes:

http://files.pierrespring.com/techzinglive_bootstrap.rss

Simply add the feed url to Advanced > Subscribe to Podcast… in iTunes and then click Get All as shown in the following image:

November 19th, 2010

Discussion 2: Dokuwiki

Pierre Spring Podcast

This is a discussion recorded at the FrOSCamp Zürich in September 2010. Andreas Gohr and Anika Henke talked about the beginnings of DokuWiki and what differentiates it from other wikis.

I myself have used DokuWiki quite a lot. I feel like it’s the wiki that best suits my needs. As the name indicates, DokuWiki has put a focus at documenting things. I’ve use it to collect snippets of code over the years, to organize my travels, to write down ideas, ect. It’s the perfect digital notebook.

DokuWiki is very, very lightweight and has well thought event system in it’s core. This makes it super easy to modify pretty much any part of the wiki using a plugin. There is a massive amount of great plugins available on the DokuWiki Plugins Page.

Over the last couple of years, I’ve tried to write a WYSIWYG plugin for DokuWiki. A project I’ve never quite completed until recently. If you’re interested in trying it out, you could fork it on GitHub. It still needs a lot of work, so why not get involved?

Be sure to listen to the podcast and try out DokuWiki. It’s clean and simple! You will love it!

November 13th, 2010

Discussion 1: Symfony2 CMF

Pierre Spring Podcast

In this very first episode of the podcast I met Lukas and Thibault in order to talk about the Symfony2 CMF.

The Symfony CMF project makes it easier for developers to add CMS functionality to applications built with the Symfony2 PHP framework. Key development principles for the provided set of bundles are:

  • scalability
  • usability
  • documentation
  • testing

In this episode, we discussed the following things:

September 20th, 2010

Dirty looping in JavaScript

Due to Function Scope and the hoisting of variable declarations we have to be a bit careful when using loops in JavaScript.

Let’s have a look the following example which is inspired by Douglas Crockford’s 3rd video on JavaScript:

var assure_positive = function (matrix) {
    for (var i = 0; i < matrix.length; i += 1) {
        //   ^ fist declaration of i
        var row = matrix[i];
        for (var i = 0; i < row.length; i += 1) {
            //   ^ second declaration of i
            if (row[i] < 0) {
                throw {
                    name: 'MatrixError',
                    message: 'Negative'
                };
            }
        }
    }
}

Due to the hoisting of variable declaration, this is the same as:

var assure_positive = function (matrix) {
    var row, i;
    //       ^ declaration got hoisted
    for (i = 0; i < matrix.length; i += 1) {
        row = matrix[i];
        for (i = 0; i < row.length; i += 1) {
            // ^ i gets reset to 0
            if (row[i] < 0) {
                throw {
                    name: 'MatrixError',
                    message: 'Negative'
                };
            }
        }
    }
}

As you can see both loops share a single variable i. This is certainly not what was intended by the programmer. A first error occurs if

matrix.length + 1 > row.lenth

In this case the script will run indefinitely. In many other cases the function will simply produce false positives, as only the first row will be examined. Let’s test this:

var try_and_alert = function (matrix) {
    try {
        assure_positive(matrix);
        alert('Ok');
    } catch (e) {
        alert(e.message);
    }

}
try_and_alert([[-1,2,3],[1, -2,-3]]); // -> alerts "Negative"
try_and_alert([[1,2,3],[-1, -2,-3]]); // -> alerts "OK" (false positive)
try_and_alert([[1],[1],[1]]);         // -> infinite loop

In addition to that, the row variable is defined in the entire scope of the assure_positive function. For now this is not harmful, but it could lead to future errors when refactoring the coed.

The described problem does not happen in languages with block scope, as each loop has it’s own scope. In order to achieve this in JavaScript, we simply need to wrap each loop into a function:

var assure_positive = function (matrix) {
    // wrapper around the loop over the matrix
    (function(){
        for (var i = 0; i < matrix.length; i += 1) {
            var row = matrix[i];
            // wrapper around the loop over the row
            (function(){
                for (var i = 0; i < row.length; i += 1) {
                    if (row[i] < 0) {
                        throw {
                            name: 'MatrixError',
                            message: 'Negative'
                        };
                    }
                }
            }())
        }
    }())
}

try_and_alert([[-1,2,3],[1, -2,-3]]); // -> alerts "Negative"
try_and_alert([[1,2,3],[-1, -2,-3]]); // -> alerts "Negative"
try_and_alert([[1],[1],[1]]);         // -> alerts "OK"

Every variable that is declared within one of the wrapper functions is only visible in the scope of this function and all it’s sub-functions. It is invisible to the enclosing scope and due to Lexical Scoping (aka Closure) we still have access to the variables defined in the enclosing scopes, such as matrix or row.

Once again, we see how powerful Lexical Scoping is. It gives us the possibility to use functions in order to simulate block scope for our loops.

May 24th, 2010

My variable declaration got hoisted

I already talked about function scope in my last blogpost. Yet to fully understand how functions scope works, it might be good to look at the hoisting of variable declarations.

To non-native english speakers like me, the word hoisting itself presents a certain mystery. Here is what Wiktionary tells us:

Verb to hoist: To raise; to lift; to elevate; especially, to raise or lift to a desired elevation, by means of tackle or pulley, as a sail, a flag, a heavy package or weight.

This is precisely what JavaScript does with a variable declaration.

The var statement

var counter = 0;

gets split into two statements:

// A var statement in which the variable counter is declared and
// initialized to undefined.
var counter;

// An assignment statement which assigns the value 0 to the variable.
counter = 0;

When we say that the variable declaration gets hoisted, we mean that the declaration part of the var counter = 0; statement is put to the beginning of the function by the interpreter, meaning that the two following functions are equal:

var f1 = function () {
   // some code
   var counter = 0;
   // some more code
}

var f2 = function () {
   var counter; // initialized with undefined
   // some code
   counter = 0;
   // some more code
}

f1 gets actually transformed into f2.

Remember how we defined function scope: A variable declared anywhere in the function is visible everywhere in the function. The hoisting of variable declarations is the reason for this.

Hoisting of the variable declarations is also the reason we recommended to declare variables in the beginning of the function in JavaScript. This is different from most C like languages, in which it is recommended to declare variables where they are actually used.

Let’s look at an example to see why declaring the variables at the top of a function is important for a better understanding of the program:

// a global variable
var counter = 0;

var f = function (data) {
   counter++;
   // so something
   for (var counter = 0; counter < data.length; counter++) {
       // do something
   }
}
f([1,2,3]);
alert(counter); // -> 0

This seems wired, right. The increment of counter++ at the beginning of f() seems to be applied on the global counter variable. But due to the hoisting of the declaration within the for(;;) loop, the increment is applied to the counter declared in the loop.

That’s it. I think that I coverd all the basics of function scope and lexical scoping in the last two posts. In my next post, I’ll show how to rewrite f in order to be able to use a counter variable within the loop and still have access to the counter from the enclosing scope.

May 20th, 2010

Of Function Scope and Lexical Scoping

Initially I meant to write an article entitled “Dirty looping in JavaScript”. The tagline of this soon to be written article was the following:

Due to Lexical Scoping and the way variables are declared and assigned values in JavaScript we have to be a bit careful when using loops.

As I was writing about loops in JavaScript I noticed that the problem was rather with Function Scope than with Lexical Scoping. And not being sure what the exact difference between Function Scope and Lexical Scoping was, I dropped my initial article in order to ask (and hopefully answer) the following questions:

What is Lexical Scoping? And how does it relate to Function Scope?

To me, Scoping is the ruleset used to lookup variable values. Especially the ones that are not declared within the current Scope. Only when you exactly know how Scoping works in your language, can you be sure about the value a variable has at any given place in your code. It is very important to understand how this is implemented in your language of choice.

Wikipedia defines Scope as follows:

Typically, scope is used to define the extent of information hiding—that is, the visibility or accessibility of variables from different parts of the program.

In JavaScript we have Function Scope and Lexical Scoping.

Function Scope means that any variable which is defined within a function is visible within that entire function. This is quite different form Block Scope, in which a variable scope is limited by the block a variable is declared in. A block is usually what you find between {curly braces} or loop variables. Block Scope is used in most of the programming languages that are currently popular. Think of a for(;;){} loop:

var i = 1;
for (var i = 0; i<10; i++){}
alert(i);
// block scope    -> 1
// function scope -> 10

Pretty simple, right. Now we know what Function Scope is. But what is Lexical Scoping?

Lexical Scoping defines how variable names are resolved in nested functions. Other names of Lexical Scoping are Static Scoping or Closure. It means that the scope of an inner function contains the scope of a parent function. Let’s have a look at the following example:

var text = 'Look at me';

var parent_function = function () {

  var inner_function = function () {
    var scream = '!!!';
    alert(text + ', ' + reason + scream);
  }
 
  var reason = "I'm an attention whore";
  var scream = '!';
 
  alert(text + scream);
  inner_function();
};

parent_function();
// alerts the two following strings, in this order:
// "Look at me!"
// "Look at me, I'm an attention whore!!!"

Look at what happens when the inner_function is called. It needs to alert all three of the following variables: text, reason and scream.

The first variable that needs to be looked up is text. This variable is neither declared in the scope of the inner_function nor in the scope of parent_function. So it takes the globally declared text.

The second variable the alert() in the inner_function needs is reason. This variable is not declared within the inner_function. Hence it is looked for in the enclosing parent_function scope where it finds the truth about my nature. "I'm an attention whore".

The 3rd variable inner_function needs to alert() is scream. It is declared within inner_function and parent_function. The alert is called in the scope of inner_function, hence it is resolved to '!!!'.

That’s almost all you have to know about Lexical Scoping. The scope of an inner function contains the scope of a parent function.

If you bare with me for a little more, you will know it all. There is a little more to it, and that little more is what makes Lexical Scoping so powerful: inner functions contain the scope of parent functions even if the parent function has returned.

Let’s look at the following example:

var adder = function (total) {

  // the following function is returned
  // and assigned to adder
  var inner_function = function (summand) {
    total += summand;
    alert(total);
  }
 
  return inner_function;
 
}(0); // <- we call the annonymous function
      //    and assign the returned function to adder

adder(2); // -> 2
adder(3); // -> 5

This is possible, because in JavaScript functions are first class objects. That means that you can pass functions as arguments or they can be returned from a function. They can also be assigned to a variable or stored in an object. Anyway, the inner_function that is returned is assigned to the variable adder. And when you call adder, that is the inner_function, it has access to total due to Lexical Scoping, even though the function that had the total. total itself was declared in the scope of a function that has returned a long time ago.

Get it? How sexy is that? Simple yet beautiful!

And that’s it. You know everything there is to know about Lexical Scoping: inner functions contain the scope of parent functions even if the parent function has returned.

May 11th, 2010

JavaScript values null and undefined

In JavaScript everything is an Object. Everything but null and undefined.

The first few times I read this, it didn’t really strike me. Simply because I had never seen or used null in my own JavaScript code. But having worked with the Google Maps API recently, I came across null and wondered what the difference between the two could be.

To be completely honest, I saw how one of my workmates used it. I shook my head, looked at him and told him the following thing in an annoyingly patronizing manner: “You know what, null isn’t part of the JavaScript language. In JavaScript we have undefined, which is the same than null in PHP” He just pointed me to some code in the Google Maps API and smiled. I was baffled by both, my ignorance and the existence of null. What could this null be. And how would it relate to undefined?

Some investigation showed what most people would have derived from the names of both these language constructs.

null is a value. Or rather a non-value. It is the value you can assign to a variable or an object property, when you don’t know what else to assign. It is often used in order to intialize an object property.

var child = {
  name: null,
  baptize: function (name) {
    this.name = name;
  }
}

In some cultures, like in Finland, this actually makes sense. Finnish children do not get a name before they are baptized. But this is an other story.

Now that you have a child object, you might want to know if the child has a name. As I mentioned in the beginning, null is not an object, so you’d expect to be able to test for something like typeof child.name != 'null'. Unfortunately, typeof null returns 'object'. This is an error in the specification of JavaScript. And it is not likely to change. As a result we end up with the following getName() function:

var child = {
  name: null,
  baptize: function (name) {
    this.name = name;
  },
  getName: function () {
    if (typeof this.name == 'object') {
      return this.name || ‘Not named yet’;
    }
    return this.name;
  }
}
child.getName(); // -> 'Not named yet.'
child.baptize('Pierre');
child.getName(); // -> 'Pierre'
child.baptize({first: 'Frank', middle: 'Alvar'});
child.getName(); // -> {first: 'Frank', middle: 'Alvar'}

So, even though null is not an object, typeof null returns 'object'. But we can take advantage of the fact that every JavaScript object is typecasted to true and null is typecasted to false.

Now we know what null is. But what is undefined? undefined is even less than null. It is the default value for variables and parameters and the value of missing members in objects:

// default value for variables
var lessThanNull;
typeof lessThanNull; // -> 'undefined'

// default value for parameters
var getType = function (p) {
  return typeof p;
}
getType() // -> 'undefined'

// value of missing members in objects
var empty_object = {};
typeof empty_object.notInitialized; // ->'undefined'

var colors = ['red', 'green', 'orange'];
delete colors[1];
typeof colors[1]; // ->'undefined'

That’s it.

Just to compare it to PHP: Every time you get undefined somewhere in your JavaScript code, PHP would return null and trigger a Notice. I personally think that JavaScript has chosen the more elegant solution.

April 25th, 2010

Hello world!

Here we go. After quite some time, I finally managed to go online with this blog. My plan is to write about the things I learn or discuss with my workmates, so it will most likely be about PHP, Javascript, HTML5, DBs and Servers. Anything we web app developers encounter daily.

I will try to write at least once a week. This should be more than enough, taken that I have a 100% job at Liip, that I record at least one podcast a week (either for entrefaces.ch or macvox.ch), that I organize the webmardi sessions once a month and that I try to be a somewhat present father of two and husband.

It seems a wee bit too much.

Anyway: Big thanks to Stefan Sicher for the design and David Aerne for helping me with CSS.

April 10th, 2010