Setting Vagrant with Yii PHP


As everyone is talking about start using Vagrant, I’m writing this post about how you can use it for Yii and customize it for other projects written in PHP.

I’m not going to tell you why are we using Vagrant, bit far point less, if some of you is interested why we need it than please look at their offical site,
Here we just want a standard development environment every team developer can use and work with it.

Have a look at what we are going to do today! it will just take few minutes 🙂

1. Installing Vagrant
2. Installing VirtualBox
3. Setting up Vagrant with my favorite box
4. Provisioning with Vagrant
5. Setting up Apache, PHP 5.X, Mysql 5.X and othe things

last but not least we need a working copy of yii framework, where you are developing your app!

1. Installing Vagrant
I’m using Ubuntu 12, I’m not going to run through how to do this in every operating system because it is out of the scope of this tutorial.
So the first thing to do is to head over to the downloads page of Vagrant and install the version fits for your operating system.
Once fully installed, the command vagrant is now available to use in your favorite terminal.

2. Installing VirtualBox
Another requirement to use Vagrant is that you have a Virtual Machine provider. This is basically just software that runs the virtual machine. I’m going to be using VirtualBox because it’s free and easy to set up. After installation you don’t need to check as much. Lets proceed!

3. Setting up Vagrant with my favorite box
Now the fun part has arrived! Vagrant is basically just a configuration file (Vagrantfile) that tells the VirtualMachine what to set up and in the end what to run. The Vagrantfile should be kept in the root of your project and should be added to Git so that anyone else who is working on the project can use the same configuration file.
Lets open our favorite terminal and move to the working directory where your project is setup.

cd /var/www/project/stowitt/front-panel/

now do:

vagrant init

Now if you open your project in a text editor, you will see the new Vagrantfile into your project.

Next thing is your need is box. When you are setting up a Virtual Machine, you need the operating system and all of that junk before you even begin. Operating system is the Vagrant box here, Vagrant provides base images of those operating system.
To download an Ubuntu box, run the following command:

vagrant box add precise32

Once done add the following lines to your Vagrantfile: = "base" = "precise32"

Now it knows which box to use and your machine is just ready?? wanna try! run the command in terminal:

vagrant up

You should see a load of output to the terminal. Vagrant doesn’t actually have a user interface so you will see only the output of every command. Now to see what is going on you can do SSH, similar to your production environment.
While it’s up do:

vagrant ssh

You are not into the virtual machine! You can do anything you want but lets type “exit” and return for now.

After ended up working on machine, we can shut it down by using the following command:

vagrant destroy

Now lets do this back:

$ vagrant up
$ vagrant ssh
$ cd /vagrant
$ ls -l

You should see a list of all the files from your project. Vagrant will automatically sync all of the files from the root of the project. Pretty cool!

4. Provisioning with Vagrant

If you have ever set up a fresh installation of Ubuntu, you will know that you have to install a load of things before you are good to go. Now that you can SSH into your machine, you can happily go about installing whatever you want to set up the machine exactly how you want it.

To set up provisioning, all we have to do is to create a shell script that will automatically be loaded when we boot up Vagrant.

Create a new file called in the root of your project (the same location where you saved Vagrantfile).

Next we need to tell Vagrant to run this file when it starts up. Open your Vagrantfile and add the following line under where you set the box: = "precise32"
config.vm.provision :shell, :path => ""

Now that we have provisioning set up, we can start adding a list of instructions for what should be provisioned whenever Vagrant is set up.

5. Setting up Apache, PHP 5.X, Mysql 5.X and othe things

Now we are ready to install anything we want on our virtual development machine. To be specific about PHP and specially Yii we are going to install these items one by one.

Open up your file and add the following:

#!/usr/bin/env bash

Now lets update Ubuntu:

apt-get update

You need to add these lines in as we go!!!

Install Vim:

apt-get install -y vim

Set up Apache:

apt-get install -y apache2
# Remove /var/www default
rm -rf /var/www
# Symlink /vagrant to /var/www
ln -fs /vagrant /var/www
# Add ServerName to httpd.conf
echo "ServerName localhost" > /etc/apache2/httpd.conf
# Setup hosts file
VHOST=$(cat <<EOF
<VirtualHost *:80>
  DocumentRoot "/vagrant/public"
  ServerName localhost
  <Directory "/vagrant/public">
    AllowOverride All
echo "${VHOST}" > /etc/apache2/sites-enabled/000-default
# Enable mod_rewrite
a2enmod rewrite
# Restart apache
service apache2 restart

Install PHP 5.X:

apt-get install -y libapache2-mod-php5
apt-get install -y python-software-properties
add-apt-repository ppa:ondrej/php5
apt-get update

Set up other PHP stuff:

# Need sudo to run the following, adding root password as "Crazy007Fox"
sudo passwd
apt-get install -y php5-cli
apt-get install -y php5-mysql
apt-get install -y php5-curl
apt-get install -y php5-mcrypt

Install cURL:

apt-get install -y curl

Install MySQL:

export DEBIAN_FRONTEND=noninteractive
apt-get -q -y install mysql-server-5.5

Install Git:

apt-get install git-core

Set up Yii:

# setup database:
echo "CREATE DATABASE IF NOT EXISTS yii_app" | mysql
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY ''" | mysql
echo "GRANT ALL PRIVILEGES ON yii_app.* TO 'yii_app'@'localhost' IDENTIFIED BY ''" | mysql
# run migration
cd /var/www/
yiic migrate
# give write permission to some directories
sudo chmod -R 777 /var/www/assets/
sudo chmod -R 777 /var/www/protected/runtime/


Final Run

Now everything got setup, but hey! how do I run the project from virtual machine. Well Vagrant makes this really easy with it’s port forwarding feature. This simply allows you to specify ports on the guest machine to share via a port on the host machine.

Add the following line to your Vagrantfile: :forwarded_port, host: 8090, guest: 80

now start your machine with vagrant up
vagrant up

Once done, on your local machine try:

http://localhost:8090 in your browser to see your project.

Checkmate you are done with your virtual machine setup and your site is running 🙂


25 Tips to Optimize Your Code

Initially I had a chance to write code optimization techniques as a hunt of compiler construction in C++ and later I decided to do this specifically for web programing languages, as I have been working on Python, Perl and Ruby to figure out which language can be better to write applications that executes faster.
I personally found Python to be better in performance then PHP, Perl or Ruby. However If you are still a PHP developer or generally write web code these 25 tips can help you lot in terms of writing fast and memory efficient applications.

1. Upgrade Your Distribution
Simply upgrading your distribution like PHP, is without a doubt one of the easiest ways to improve PHP performance. In addition to the usual bug fixes and new features, each new PHP release ships with optimization improvements which can produce noticeable performance enhancements.

2. Use Native Functions
As much as possible, try to use native PHP functions rather than writing your own functions to achieve the objective. For example, you can use range( b, k) to get an array of alphabets starting from b to k in sequence, if it is only needed once in the script rather than declaring an array with these values in a function and returning it on its call.

3. Take Advantage of Native Extensions
PHP has long been accused of including everything but the kitchen sink, and in recent years the development team has made great strides in terms of stripping the core distribution of optional and redundant features (such as deprecating the redundant POSIX Regex library in preference of the PCRE library). Even so, the sheer number of available libraries and other extensions can be overwhelming, leading some developers to consider implementing their own solutions rather than invest the time investigating what’s already available.
For instance it might be tempting to spend a few hours writing a custom library capable of parsing XML, despite the availability of SimpleXML. Doing so ignores the many hours of troubleshooting and optimization already put into the native extensions, thereby almost guaranteeing the substandard outcome of any such custom solution. For this reason and others you should always investigate the availability of an existing library or extension before setting out to reinvent the wheel.

4. Use a PHP Accelerator
Barring outside interference, a PHP script executes after being “compiled” by the PHP engine, which turns the PHP code you’ve written into machine language, known as operation code (opcode). If the PHP script repeatedly churns out an identical result, then why not skip the compilation process altogether?
You can do exactly this using a PHP accelerator, which caches a PHP script’s compiled machine code, allowing the code to immediately execute upon request rather than after a potentially expensive compilation process.
Several opcode caching solutions are available to PHP developers, including notably APC (Alternative PHP Cache), an open source accelerator available for installation via PEAR. Another popular solution is Zend Server, which incorporates not only opcode caching, but also full and partial page caching utilities.

5. Use Late Static Binding
If a method can be static, declare it static. Speed improvement is by a factor of 4. As of PHP 5.3.0 Late static binding introduced, a new use for the static keyword, which addresses this particular shortcoming. When you use static, it represents the class where you first use it, ie. it ‘binds’ to the runtime class.
For example this will blow the code execution:

abstract class Builder {
    public static function build() {
        return new static;
class Member extends Builder {
    public function who_am_i() {
        echo 'Member';

6. Performance of FOR vs FOREACH in PHP
My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy… The time difference is going to be minimal in most cases.
For some reasons I decided to do a quick benchmark run…

$a = array();
for ($i = 0; $i < 10000; $i++){
$a[] = $i;

$start = microtime(true);
foreach ($a as $k => $v){
$a[$k] = $v + 1;
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v){
$v = $v + 1;
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you’re modifying the array in the loop, it’s several times faster to use references…

7. Frequently Used Switch Cases
Keep most frequently used switch cases on the top. A switch statement is not always faster than an if statement. It scales better than a long list of if-else statements as switch can perform a lookup based on all the values. However, for a short condition it won’t be any faster and could be slower.

8. Conditions that uses = = =
Use “= = =” instead of “= =”, as the former strictly checks for a closed range which makes it faster.

9. Pass Reference to Function
Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.
For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.

// passing by reference
function  computeValue( &$param )
// Something goes here
foreach( $param as $k => $value)
$param[$k] = $value + 1;
$x = array();
for( $i =0; $i<99; $i++)
$x[$i] = $i;
computeValue( $x);

// array with 100 elements each incremented by 1
print_r( $x );

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

// passing by value
function  computeValue( $param )
// Something goes here
foreach( $param as $k => $value)
$param[$k] = $value + 1;
return $param;
$x = array();
for( $i =0; $i<99; $i++)
$x[$i] = $i;
// array with 100 elements each incremented by 1
print_r(computeValue( $x));

10.    Use Caching Techniques
Use cache to reduce the load of database operations as well as the script compilation. We can use memcache for the reducing database load and APC for opcode caching and intermediate code optimization.

11.    Use Single Quotes
Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” ) if you are going to keep only the string inside it avoiding any variables. Double quotes checks for the presence of variable and adds little bit of overhead.

12.    Use Appropriate String Functions
str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

13.    Calculate Only Once
Calculate and assign the value to the variable if that value is getting used numerous time rather than calculating it again and again where it is being used.
For example, the following will degrade the performance.

for( $i=0; i< count($arrA); $i++)
echo count($arrA);

The script below will perform much better.

$len = count($arrA);
for( $i=0; i< $len; $i++)
echo $len;


14.    Disable Debugging Messages
File operations are a bit expensive if you are using it quite often in code. So, if you are calling lot of custom functions to log errors and warning during your development process, make sure you remove them before you push the code to production.

15.    Use Methods in Derived Classes
Methods in derived classes are faster than base classes. For example, let there be a function in both base class and derived class for performing task1. It is named as “forTask1? in base class and “forTask1again” in derived class, so that they will not override.
Call to the function “forTask1again( )” which is in derived class will work faster than call to the function “forTask1( )” as it is from base class.

class someBaseClass
public function forTask1($string)
// perform task 1
public function forTask2( )
// perform task 2

class derivedClass extends someBaseClass
public function forTask1again($string)
//perform task 1 same as the function in base class.
public function forTask3($string)
//perform task 3

//Instantiating the derived class below.
$objDerivedClass = new derivedClass( );

// The call below works slow for task1 as it is from base class.
$resultTask1 = $objDerivedClass->forTask1( );

// The call below works faster for task1 as
// it is from derived class.
$sameResultTask1 = $objDerivedClass->forTask1again();


16.    JSON Vs. XML
Use JSON instead of XML while working with web services as there are native php function like json_encode( ) and json_decode( ) which are very fast. If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

17.    Use isset
Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.
For example, let us assume that you have a function which returns an array with values or a NULL array. Now you want to check whether the returned array is with values or not, then use the following:

// do something here
In this case, use the above code block, instead of the following:
if(count($returnValue) > 0)
// do something here


This will also be fast to execute:

// Checking if string length is 5

18.    Pre increment vs Post increment
Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as – See more at:

$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn’t any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can’t really confirm this. Furthermore, it really doesn’t makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

19.    Absolute Path VS Relative Path
Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn’t. Well, that’s the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

20.    Dot Vs Commas Concatenation
Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below:

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a , $b;

21.    use gzip compression
Use ob_start() at the beginning of your code. This gives you a 5-15% boost in speed for free on Apache. You can also use gzip compression with ob_gzhandler() for extra fast downloads (this requires spare CPU cycles).

22.    Use unset in larger scripts
unset() variables that are not used anymore to reduce memory usage. This is mostly useful for resources and large arrays.

23.    Reduce Number of Hits to DB
Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times. For example:

if (mysqli_connect_errno())
echo "Failed to connect to MySQL" ;
function insertValue( $val ){
mysqli_query($con,"INSERT INTO tableX (someInteger) VALUES ( $val )");
for( $i =0; $i<99; $i++){
//  Calling function to execute query one by one
insertValue( $i );
// Closing the connection as best practice

The script above is much slower than the script below:

if (mysqli_connect_errno())
echo "Failed to connect to MySQL" ;
function insertValues( $val )
// Creating query for inserting complete array in single execution.
$query= " INSERT INTO tableX(someInteger) VALUES .implode(',', $val)";
mysqli_query($con, $query);
$data = array();
for( $i =0; $i<99; $i++)
// Creating an array of data to be inserted.
$data[ ]  =   '(" ' . $i. '")' ;
// Inserting the data in a single call
insertValues( $data );
// Closing the connection as a best practice

24.    Tune your Database
Tune your database and index the fields that are commonly used in your SQL WHERE criteria. ADOdb, the very popular database abstraction library, provides a SQL tuning mode, where you can view your invalid, expensive and suspicious SQL, their execution plans and in which PHP script the SQL was executed.

25.    For MySQL use relevant Storage Engine
Distribute your tasks into reading or writing. Use relevant Storage Engine for reading and writing. Slow writing can go to background process. Use temporary tables to boost writing.

If software developers were construction workers

Here is the diary of a construction worker that works in some enterprise construction company (let’s call it Concrete-Harderware (r) inc)

March 1 Huray! We got the contract to build a twelve story high commercial building. We’re all enthusiastic about the new job. We drank seven or eight six-packs of beer, celebrating.

March 2 The client doesn’t appear to like the expression “when it’s done it’s done”. He wants us to use more accurate deadlines. Poor sap. He obviously doesn’t understand high-technology.

March 3 We discussed the deadlines. We drank about eleven six-packs. Peterson said that we will probably be ready in four months. So – eight months. We wrote twelve months in the contract but we’ll probably be done in sixteen.

March 6 Peterson returned the beer-cans for recycling.

March 8 We celebrate the International Women’s Day. There are no women in the company, so nobody spoils the party.

April 2 Peterson said that we had better start working. What’s wrong with that guy? Anyway, we cleared the construction area and hung nice posters saying “The construction is performed by Concrete-Harderware inc. (”. Now having fulfilled our duties we play Quake.

April 20 The client came to ask how things were going. We had him play Quake with us and let him beat us all.

April 21 We discussed the project. Michaels says to use pre-made concrete blocks. Peterson insists that we must build it the old-fashioned way – with bricks. Alex – the new guy – came up with a rather radical approach – to build a few dozen wooden shacks and connect them with tunnels. It was the new thing everybody was talking about. We had to remind him that the client wants a twelve-story building. We tried to settle to a solution with 1vs1 matches in Quake. Alex and his bungalows fell quickly but Peterson and Michaels tied. We decided that each of them should build half a building with his method and then connect the two halves.

April 30 The first floor is ready. We showed it to the client. He inquired why the ceilings in different rooms are at a different height, why there are bricks falling from the walls, and why there is no door and you have to come in through the windows. We explained that these are shortcomings of the beta-version. Proud of ourselves, we went celebrating.

May 10 Peterson got sober and cursed a lot. We thought that Alex had drunk all the beer but it turned out to be worse. We had forgotten to put the foundation. It was written in the project files but who reads specs nowadays?

May 11 We demolished the first floor. Que sera, sera…

July 11 We are working hard! Peterson is finishing the second floor, Michaels is working on the sixth. Alex has build the elevator shaft up to the ninth floor but it shakes menacingly when it’s windy. We had to put some wooden scaffolding around it.

July 17 Alex is building the roof and the terraces. On the ground. We will use a crane to lift them later.

August 13 Michaels’ concrete blocks don’t meet up. There are a few holes three feet wide. He asked Peterson for help but Peterson said he had already more than enough to do and, besides, without knowing the internal architecture of the concrete blocks, one cannot do anything.

August 14 We broke up a few concrete blocks so Peterson could study the internal architecture. Peterson cursed a lot and said that the developers of the blocks are complete idiots.

August 17 Peterson plugged the holes between the concrete blocks with some bricks. The blocks are now a little crooked and there are a lot of little holes instead of few big ones. Peterson put some duct tape on the holes and said that it’s fine as long as it isn’t raining.

September 1 The concrete block company released some new blocks – more stable and robust and with built-in file cabinets on the walls. But the truth is that they are incompatible by form with the old ones and are three times as heavy. Who makes these stupid mistakes?

September 16 Alex came in, full of ideas. He suggested making all windows with different sizes. The client was going to love them. We told him to shut the f*** up.

November 2 Peterson reached the fifth floor. He is proud of himself. We drew his attention to the fact that the walls are in a forty degree angle. He cursed a lot, then he said that we were idiots and don’t understand anything. He promised to think about it.

November 3 The client came in today. He asked why the walls were in a forty degree angle. We explained to him what the Coriolis Effect is. He listened to us and said the he isn’t a building expert but next to his house there was a building just like this and the walls were straight. Then that moron – Alex, started talking to him and explained to him the idea for the different-sized windows. The client, naturally, liked it. God damn it!

November 4 We asked Alex if we had to break everything up because of his windows. He assured us that there is no need. The concrete blocks had an undocumented feature.

November 5 Peterson finally admitted that there is something wrong with the walls. He said that he had laid some brick not the way it was supposed to be, but to find out which he needs to check them all. He said that it’s easier to build everything from scratch.

November 6 We tried to convince Peterson that there is no time to build everything from scratch. We showed him calculations made with a computer. Peterson cursed a lot. He said that the computer was designed by idiots.

November 7 Peterson agreed to make everything from concrete blocks and then went to drown his misery in alcohol.

November 8 We demolished the brick part. We damaged some parts of the concrete part. The whole building creaks and shakes menacingly. We put some wooden struts on it and went to play some Quake.

November 17 Peterson came back from the drinking. We are working hard.

November 11 We celebrate Remembrance Day. There are no Canadians in the company, so nobody spoils the party.

November 15 We remembered that the crane goes up only to the eighth floor. We sent Michaels for a new one. We are playing Quake. Alex just beat Peterson. There is a new generation growing…

November 24 Michaels came back. He hasn’t found a crane but he has brought an excavator. He suggested that we dig a hole and finish the building downwards. He said that in the contract it’s not said that all the floors should be above the ground.

November 25 We brainstormed the crane issue. At last can of beer we found a solution. We put off the main construction. We will build a four-story building and then put the crane on top of it.

December 25 We celebrate Christmas. Santa doesn’t work in the company so nobody spoils the party.

January 14 I don’t remember anything. My head hurts.

February 4 We are ready with all twelve floors. Tomorrow we put the roof that Alex built.

February 5 Alex is an idiot! The roof keeps falling. We propped it up with the crane for now. We’ll think what to do.

February 6 Alex said he’s innocent. It’s just that Michaels’ twelfth floor is 10 feet wider and 8 feet longer than Peterson’s twelfth floor. Obviously they’ve been using different concrete blocks. But Alex is an idiot nevertheless. His damn roof doesn’t fit any of the floors. The elevator shaft, too.

February 7 We glued the roof. Peterson said that it’s fine as long as it isn’t snowing.

February 8 It started snowing…

12 Steps to Better Code – The Joel Test

Have you ever heard of SEMA? It’s a fairly esoteric system for measuring how good a software team is. No, wait! Don’t follow that link! It will take you about six years just to understand that stuff. So I’ve come up with my own, highly irresponsible, sloppy test to rate the quality of a software team. The great part about it is that it takes about 3 minutes. With all the time you save, you can go to medical school.

  1. Do you use source control?
  2. Can you make a build in one step?
  3. Do you make daily builds?
  4. Do you have a bug database?
  5. Do you fix bugs before writing new code?
  6. Do you have an up-to-date schedule?
  7. Do you have a spec?
  8. Do programmers have quiet working conditions?
  9. Do you use the best tools money can buy?
  10. Do you have testers?
  11. Do new candidates write code during their interview?
  12. Do you do hallway usability testing?


Multi level navigation using backbone.js

Making multi level nested ul li navigation is not much difficult, Heres the code below to make an nested navigation.

<!DOCTYPE html>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>

    <script type="text/template" id="parent-template">
        <ul id='ul-<%= parent_id %>'></ul>
    <script type="text/template" id="child-template">
        <li id="li-<%= id %>"><%= name %></li>

    <script type="text/javascript">

    var compiledParent = _.template( $('#parent-template').html() );
    var compiledChild = _.template( $('#child-template').html() );

    var data = [

    var NestedView = Backbone.View.extend({
      render: function(){
        this.$el.html( compiledParent({parent_id : '0'}) );
        this.collection.each( function( model ){ this.renderElement( model ) }, this )

      renderElement: function( model ){
        var ul = this.getParentUl( model );
        this.appendElement( ul, model );

      getParentUl: function( model ) {
        var ul = this.$el.find( "#ul-" + model.get( "parent_id" ) );
        if( ul.length == 0 ) {
          this.appendListInElement( model );
          ul = this.$el.find( "#ul-" + model.get( "parent_id" ) );

        return ul;

      appendListInElement: function( model ){
        var li = this.$el.find( "#li-" + model.get( "parent_id" ) );
        li.after( compiledParent({parent_id : model.get( "parent_id" )}) );

      appendElement: function( ul, model ){
        ul.append( compiledChild({id:model.get( "id" ) , name:model.get( "name" )}) );

        var elements = new Backbone.Collection( data );
        var nestedView = new NestedView({ el: "#wrapper", collection: elements });
    <div id="wrapper">

Facebook application’s iFrame to auto resize

If you have a Facebook iFrame application and you want to auto resize the ifram and have read Facebook’s horrible documentation for their js sdk and have tried so many different variations – all of them not working at all. This code will work for you!

<!DOCTYPE html>
<html lang="en">
<script type="text/javascript">
window.fbAsyncInit = function()

    <!-- Some of your html code -->
    <div id="fb-root"></div>
    <script type="text/javascript" src=""></script> 
    <script type="text/javascript">

        appId: 'xxxxxxxx', 
        status: true, 
        cookie: true, 
        xfbml: true

    /* Init fb Resize window */

    /* Completly removed now in JS SDK*/
    /* FB.Canvas.setAutoResize(7); */

    /* As of Jan 2012 you need to use */


PHP Class & Function Comments

If you have seen that some PHP functions and classes are commented at the top, using a format like this:

 * Convert an object to an array
 * @param    object  $object The object to convert
 * @return   array

So you might be interested what is this format of commenting and where can you find some information on it? so here I tell about commenting PHP functions and class in short!


 * Does something interesting
 * @param  Place    $where  Where something interesting takes place
 * @param  integer  $repeat How many times something interesting should happen
 * @throws Some_Exception_Class If something interesting cannot happen
 * @return Status


 * Short description for class
 * Long description for class (if any)...
 * @copyright  2006 Zend Technologies
 * @license   PHP License 3.0
 * @version    Release: @package_version@
 * @link
 * @since      Class available since Release 1.2.0

That’s basically phpDoc syntax.

You can read more here: phpDocumentor