PHP vs. Node.js

TL;DR: PHP is not going to disappear immediately, but its positions are undermined even further by the nascent Node.js.

When the Internet exploded in the 2000s, PHP was a thing all the cool kids did. It was extremely revolutionary, because:

  • It was an interpreted language unlike C++ or Java which require the source code compilation
  • It had the ability to be used directly with HTML by mixing within its template files with a <%php ... %> markup tags
  • It had cheap shared hosting providers on Apache servers with a Linux, Apache, MySQL and PHP (LAMP) stack
  • It had a functional nature which is easier to learn than the object-oriented programming

Over the years, PHP and its apps became a monstrous technology vulnerable to security threats (e.g., SQL injections), lack of a centralized packaging registry (was Composer inspired by Node Package Manager?), inconsistent API and subpar performance. There are many better alternatives to PHP, e.g., Ruby on Rails and Django, however nothing is as approachable as Node.js.

For those of you who aren’t familiar with Node.js, or who have heard of it but can’t quite grasp the concept, here is my analogy:

Node.js is functionally similar to the PHP + Apache or ASP + IIS stacks.

Nowadays, Node.js is gaining momentum. The platform uses JavaScript. It’s functional, and its non-blocking I/O mechanism allows for a better performance. Node.js comes with a robust Node Package Manager solution and the specification, i.e., ECMAScript.

Because Node.js is a lower-level technology, it is not comparable to complex frameworks like Struts, Rails or Django directly.

Therefore, many people, whether software engineers or entrepreneurs, are often faced with the decision of “What tech stack to use” In this article PHP vs. Node.js, we’ll compare apples-to-apples approaching the question from different angles, such as:

  • Syntax
  • Context switch
  • Modules
  • Ecosystem
  • Frameworks
  • Real-time apps
  • Database apps
  • Third-party services apps
  • Web servers
  • Hosting
  • Performance

Syntax

Both platforms have access to the command line interface via $ php -i and $ node.

This snippet prints ‘Hello World’ in PHP:

echo 'Hello World'; 

This will output the same phrase in Node.js:

console.log('Hello World');

Note: In JavaScript semi-colons are optional except when inside of the for loops and before immediately-invoked function expressions (IIFE).

Sleep function script example in PHP:

echo "a"."\n";
sleep(2);
echo "b"."\n";
echo "c"."\n";

The above code will output:

a

And then after a 2 second delay:

b
c

If we try to re-write the code in Node.js:

console.log('a')
setTimeout(function() {
  console.log('b')
 },2000)
console.log('c')

This snippet will print:

a
c

And with a 2 second delay, it will print:

b

Note: In JavaScript, console.log() automatically adds the end of line symbol.

The for loop in PHP might look like this:

for ($i = 1; $i <= 10; $i++) { 
  echo $i;
} 

They’re strikingly similar in Node.js:

for (var i = 0; i <= 10; i++) { 
  console.log(i);
} 

To create an array in PHP:

$users = array( 
  array('name' => 'John', 'id' => 3940), 
  array('name' => 'Peter', 'id' => 8904) 
); 

To create an array in Node.js:

var users = [ 
  { name: 'John', id: 3940 }, 
  { name: 'Peter', id: 8904 } 
] 

To iterate through an array in PHP:

for($i = 0; $i < count($users); ++$i) { 
  $users[$i]['id'] = mt_rand(000000, 999999); 
} 

To iterate through an array in Node.js:

for (var i; i < arr.length; i++) {
    users[i] = Math.floor(Math.random()*1000000);
} 

Or in a functional manner:

users.forEach(function(user, i){ 
  users[i] = Math.floor(Math.random()*1000000); 
}) 

To declare a function in PHP:

function hello($name) {
  echo "Hi ".$name;
}
hello("Peter"); //outputs Hi Peter

To declare a function in Node.js:

function hello(name) {
  console.log('Hi' + name);
}
hello('Peter'); //outputs Hi Peter

To declare a new object in PHP:

class foo {
    function do_foo()  {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();

To declare a new object in Node.js:

var foo = function () {
  return { 
    do_foo: function () {console.log('Doing foo');}
  };
};

var bar = foo();
bar.do_foo();

Note: there are no classes in Node.js/JavaScript, because objects inherit directly from other objects (prototypal inheritance). There are many instantiating patterns such as pseudo-classical, functional(above) and classical.

A database snippet with the PDO database connection library in PHP:

$pdo = new PDO('sqlite:users.db');
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); //<-- Automatically sanitized by PDO
$stmt->execute();

A Node.js database script with the Mongoskin MongoDB library:

//assuming we use Connect/Express middleware for req.query
var db = require('mongoskin').db('localhost:27017/db'); 
db.collection('users').find({_id: req.query.id}).toArray(function(err, results) {
    if (err) throw err;
    console.log(results);
});

Context Switch

The Switch between different environments and languages is attributed to the drop of efficiency when writing software code. Many researches and personal anecdotal observations show that interruption negatively impacts programmers’ performance. With less languages to learn and remember the flow is smoother and the code is better! For a deeper articles on this subject you might want to take a look at Human Task Switches Considered Harmful and The Multi-Tasking Myth.

PHP

With the LAMP stack, i.e, Linux, Apache, MySQL and PHP, developers must master at least two more languages which are PHP and SQL in addition to the mandatory and omnipresent HTML, CSS and JavaScript.

Node.js

Node.js is brilliant at having less context switches, because together with MongoDB, this stack can operate only in one language: JavaScript!

An example of MongoDB shell commands (called by $ mongo):

> db.users.find({});
> db.users.insert({name: 'Azat', email: 'azat@rpjs.co'})
> db.users.update({name:'Azat'},{$set:{email:'hi@rpjs.co'}})

Modules

PHP

There is PEAR, a veteran system which installs packages on a server globally, and a better alternative Composer.

In other cases, developers had to seek modules — or components as they call them — on various websites, and to administer them manually by placing *.php files into sub-folders of their projects. Unfortunately, all this is not very kosher.

Node.js

Node.js comes with a superior and dependable package management system called NPM and its registry npmjs.org which is easy to use and publish. Everything is administered via the package.json file and versioned locally, unless we’re installing a CLI tool with the -g option.

Both PHP and Node.js are functional languages with a relatively later addition of OOP to PHP.

Ecosystem

PHP

This is probably one of the most important areas where PHP still beats Node.js. There are amazing open-source applications, e.g., WordPress, tons of free scripts, quality tools and books.

Node.js

Node.js is growing faster than any other platform/language. This is mostly due to the philosophy of keeping modules minimal and performing only a small set of tasks. Other factors might include such things as:

  • The gigantic popularity of front-end JavaScript among web developers
  • Existence of the specs, and abundance of JavaScript resources and gurus (such as Doug Crockford) amassed during the language’s many years of existence
  • Collaborative GitHub open-source community based on an awesome distributed version control system that didn’t exist before
  • Ease of NPM use, e.g., to publish an NPM module run $ npm publish

As a result, some people predict that Node.js will surpass other languages in the absolute number of contributions.

Frameworks

It’s important to have rich tools and proven libraries at our disposal.

PHP

CakePHP and Zend come to mind, and for more choices there is an extensive list.

Node.js

Playing field is relatively leveled with Express.js being the most popular choice, and the full-stack MVC frameworks Meteor and Derby showing the way to the future.

Real-time apps

PHP

For PHP, there is still Node.js dependent Elephant.io and some other approaches. The problem with native PHP and websockets is that Apache and ISS — where PHP is usually run as a module — weren’t really built with persistent connection in mind. Therefore, developers have to use the standalone processes like: Apache WebSocket or Ratchet.

Node.js

Real-time apps building is just a breeze with Node.js stack of the Socket.IO library, Express.js framework and Handlebars reactive template engine. In the Meteor and Derby projects, real-time apps building is taken one step further by combining front and back-end code bases with the persistence layer which reduces the complexity and speeds up the development dramatically.

Database apps

PHP

PHP has a long and fruitful history with traditional/relational databases like MySQL, hence the name of the stack LAMP — Linux, Apache, MySQL and PHP.

Node.js

Node.js is natural with NoSQL databases like MongoDB.

The databases’ performances are somewhat comparable to each other depending on the use cases as per MySql vs MongoDB performance benchmark(MySQL), Simple Test : MongoDB vs MySQL(MongoDB) and MongoDb vs MySql – Fight!!!(MongoDB) articles. However, MongoDB is superior for distributed databases and is highly scalable. The added bonus is that without a fixed schema, NoSQL databases are perfect for cloud computing, prototyping and agile projects.

Third-party services apps

PHP

As is the case with many traditional languages, PHP’s flow is blocked ’til the remote server has responded, hence the need for multi-threading.

Note: Some languages provide this feature when special libraries/frameworks such as EventMachine for Ruby or Twisted for Python are used. However, they’re very complex and weren’t built from the ground up with the platform.

Node.js

On the contrary, due to a non-blocking I/O, Node.js can handle multiple requests and make multiple requests as a client to a third-party services (e.g., Twitter, Amazon) with just one thread of execution.

Web Servers

PHP

Since PHP 5.4 and higher, there is a build-in development server that we can started with:

$ php -S localhost:8000

Assuming we have index.php in that folder:

<?php
  echo 'Hello World';
?>

For versions prior to 5.4, there are ‘all-in-one’ tools like MAMP and XAMPP.

As for the production environment, PHP can’t be run on its own. One of the most popular technologies used with PHP are Apache and nginx where PHP is just a module of Apache web server. My personal experience of Apache is that it has a steep learning curve and while being very configurable, by default those configurations are prone to security leaks.

Node.js

Node.js was created from the ground up for the network applications and there is a set of core modules to write web servers.

To start a Node.js server:

$ node .

Assuming our index.js file in this folder has:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

In production, Node.js can be run on SmartOS or Linux (like Ubuntu) as a service.

Note: Multi-threading is absolutely possible in Node.js with clusters and/or external modules.

Hosting

PHP

PHP owes its popularity mainly to the ease and cheapness of offered shared hosting solutions. True, it’s hard to find one without the LAMP stack on it. This commoditization sometimes leads to security holes and less than acceptable downtime due to hosting providers overselling and other consumers using malicious code.

Platform as a Service is a better alternative and somewhere in between full fledged dedicated server and shared hosting. Most of PaaS providers support PHP right of the bat.

Node.js

Node.js works nicely on PaaSs, with Heroku and Nodjitsu leading the list. Also, the cloud infrastructure company Joyent (the maintainer of Node.js), developed powerful operation system SmartOS that allows for performance bursts, painless deployment and DTrace debugging.

Performance

It’s needless to say that performance is important. This resource shows different benchmark tests: Which programs are fastest?.

PHP

PHP is relatively fast but due to its bottleneck in the file system, database and third-party requests, it fails miserably in comparison with Node.js and its super fast Goolge Chrome V8 engine.

For example, when Facebook reached its scalability limits with PHP, they wrote an extremely fast C++ library and virtual machine which they called HipHop VM, but kept the PHP API.

Node.js

Node.js is extremely fast due to its non-blocking I/O mechanism and Google Chrome V8 engine technology. I even heard that Joyent started re-writing some of their C++ modules in Node.js.

Conclusion

PHP was an outstanding technology in its days. Its success and popularity came from:

  • Its ease of learning and use
  • cheap and straightforward hosting mostly shared LAMP
  • Abundance of open-source scripts, apps and libraries

At the same time, these same things now led to its dusk. The contributions to the core from beginner programmers metamorphosed API inconsistently while the lack of OOP/classes and module management systems inhibited open-source community growth. Absence of a leading framework (Ruby on Rails comes to mind as an example of a single dominance) or a paradigm that also helped to produce a lot of bad code that relied heavily on mixing PHP and HTML code without any MVC-ishness. On the other hand, there are a lot of good products and infrastructure for PHP that are here to stay.

Node.js is relatively young with only three years since its first commit, but it’s already the fastest growing platform by the pace of contributions (the absolute number will surpass other languages in a few years). The fact that JavaScript language is the most popular language in the world and has the biggest run-time internment of course attributed to that. Many tools are ported to Node.js with small or no modification from the browser environment. Also, great books on JavaScript fundamentals (for example, JavaScript: The Good Parts and Eloquent JavaScript) experienced surge in the popularity again.

Node.js is very efficient and great for building real time, NoSQL oriented and scalable systems.

Disclaimer

I worked with many technologies including Ruby on Rails, Python, Java/J2EE, VB, ASP, Perl and of course PHP. One of my most complex PHP projects was openList.co which involved use of the MVC pattern with template engines, classes, database abstraction layer and .htaccess re-routing. However, my focus during the past couple of years has been dedicated solely to Node.js and front-end JavaScript frameworks like Backbone.js. So my opinion might be biased, please comment on your experience with real projects in both PHP and Node.js.

If you want to learn more about Node.js take a look at my artisanal book Rapid Prototyping with JS: Agile JavaScript Development, premium online training Node Program (Udemy link) and the astonishing coding intensive full-time course at HackReactor.

Author: Azat

Techies, entrepreneur, 20+ years in tech/IT/software/web development expert: NodeJS, JavaScript, MongoDB, Ruby on Rails, PHP, SQL, HTML, CSS. 500 Startups (batch Fall 2011) alumnus. http://azat.co http://github.com/azat-co

88 thoughts on “PHP vs. Node.js”

  1. Good article but you are missing some of the great uses of Javascript/NodeJs: namely in databases!!!

    The use of Javascript is not reduced to Document Stores like MongoDb, you can use it in PostgreSQL thanks to the procedural language Plv8js (http://pgxn.org/dist/plv8/doc/plv8.html) to manipulate data
    and also store/query/manipulate Json datastructures (http://www.postgresql.org/docs/9.4/static/datatype-json.html)

    And ORMs are fast improving/maturing in NodeJs for relational databases, Sequelize (http://sequelizejs.com/) and Knex/Bookshelf (http://bookshelfjs.org/)

    PostgreSQL is a much more robust and scalable database, it does Relational and Document Store and you can go (almost) all the way Javascript?NodeJs with it!!

  2. I personally do not hate PHP, I just hate the community for it is mainly a bunch af amateurs. I have, as an inexperienced developer, been working with PHP in an enterprise environment with mediocre programmers. I always thought: “WTF, this code cannot be right. It is neither beautiful nor does it fulfill its duty elegantly or efficiently.” But of course I could not explain why that was. Now I can: This was due to the fact that my fellow workers were as bad as me, they did not know better. But remember, this was in an enterprise environment, not some fancy site for auntie Gretchen’s cake recipes. And when I became better I understood what was wrong with the code. And I still work there and my fellow programmers did not advance since then. Which leads again to my initial argument: PHP coders are a bunch of amateurs.

    Part of being a programmer is to strive to always become better… and I do not see that in a lot of PHP coders. They frown upon interfaces and their best answer for code reusability is “extends”. I have since then mastered design patterns, best practices and actually switched to static languages (besides JS, which I also work with).

    Why is PHP doomed? Easy… it is the same reason why Adobe Flash dies/is dying: There is technology and standards that make the featureset of PHP obsolete:
    You want realtime comm between browser and server? Webworkers (HTML5) and Node.js.
    You want your data sent over the wire by means of REST: Express! PHP failed to deliver a very easy solution/library to this problem until now. And REST is the future for service oriented architectures… for the next few years.
    You need to have asynchronous/multithreaded processes that do some serious business/number crunching? Play Framework (Java / Scala)!
    You need scalability? Java! Read why Twitter ditched PHP, and stop using of HipHop. HipHop was developed out of necessity. Rewriting FB’s codebase would have had a bigger impact than creating a VM for PHP. That much to PHP’s scalability.

    I am very thankful for what PHP has done for the intarwebz, but now it can go home. It started as a language for dynamically creating HTML tags and content… nowadays you do not change the HTML prior to delivering. You change the DOM constantly on the fly… with JS.

    And building servers with PHP as a middleware? That has not been seen in a long time. Thus is the factors that will lead to PHP’s demise. And the fact “Easy to learn” does not bode well for future generations of coders that need to make the intarwebz a better place. I want coders that strive for excellency and rather learn C than PHP. “Easy to learn” is no argument that makes a language good. Even using this argument is actually… well… it would sound like it fits into the mindset of a PHP coder.

  3. To reply to Cas, who said: ” The PHP is an array with array’s inside.
    The other one in an array with objects inside. ”

    The PHP code shows an array containing associative arrays. The JS code shows an array containing objects. It’s important to note that 1) arrays and associative arrays differ; and 2) JS does not has associative arrays.

    Objects in JS are quite similar to associative arrays in PHP. You can call both as the author defined them similarly. In PHP:

    $users[0][‘name’];

    and in JS:

    users[0][‘name’];

    As you can probably find by testing this, they both look extremely similar and work alike.

  4. I agree, but php is changing and evolving, an example is Phalcon Framework and new JIT enviroment to php 7, Phalcon Framework is a web framework but writing on C as Extension, it was very powerful and fast containing more tools and helps, Sush as Complete MVC, ORM with (HQL), Template Engine(Volt), Migrations, etc. I leave to you a comparison made for me between Phalcon Framework and Node.js with Express framework: https://www.youtube.com/watch?v=q2DYd_fIoto&feature=youtube_gdata

  5. $users = array(
    array(‘name’ => ‘John’, ‘id’ => 3940),
    array(‘name’ => ‘Peter’, ‘id’ => 8904)
    );

    is not the same as:

    var users = [
    { name: ‘John’, id: 3940 },
    { name: ‘Peter’, id: 8904 }
    ]

    The PHP is an array with array’s inside.
    The other one in an array with objects inside.

  6. As a recent forced convert of PHP to Node, I think this article serves as a good base for comparing the two, though I’m not sure about the subliminal messaging that it’s going to replace PHP en-masse any time soon. That said, I do think it misses a few of quirky differences in Node.

    While there might be less context switching of physical languages, the issue with Node is switching between sync and async paradigms. In addition: Javascript’s two-edged sword of block scope (both a friend and foe), and, of course, the highly variable nature of `this`. You have to be constantly on your guard in Node. On top of that, you have different conventions and paradigms with which to handle callbacks (the ‘err’ first argument convention), or else we get into the use of promises for more modern code. Trying to catch thrown errors in Node is a hair pulling experience the first time round. Oh, and then there’s all the coffee script polluting JavaScript solutions you might find in a search result (a bit like looking for a CSS trick and all you find is SASS snippets – if I wanted SASS I would have asked for it).

    In terms of OOP, JavaScript does not support the `protected` scope (it’s not really necessary in JS, but if you are coming from PHP thinking, you are going to miss it), and that leads to quite significant differences in how to treat inheritance (my rule of thumb – try and avoid it if you can in Node).

    Next is that Node is generally really hard to debug. The inheritance tree in PHP generally allows you to isolate code more easily that the prototypical nature of JavaScript (try debugging Express code sometime when the offending lines are buried two or three levels deep in dependencies – not to mention the fact it overloads the `get` method – seriously?). You also have to restart the entire application just to change a file (compared to PHP where restarting Apache is rare for development). Ok, watchers handle that but it seems foreign to the PHP conditioned mind (we only need to watch CSS files in a PHP application don’t we?).

    The PHP developer needs to note that dependencies are handled a bit different to Composer. Node allows each module to support it’s own version of code, so you can end up with a huge amount of almost-duplicate code in your deployment.

    I think the Interface construct would be a valuable addition of Node, and I think that the concept of dependency injection is underutilised in the Node world, probably due to the fact that design patterns are more tightly woven into the culture of classical OOP languages like PHP (I hope this changes over time – Angular seems to be thinking in the right direction).

    Finally there is the issue of documentation. My observations are that PHP developers, on average, pay better attention to DocBlocks that Node or Javascript developers. A lot of work could be done to document callback signatures better (yeah, like by returning promises instead). And while we are on the subject, the PHP developer has a coronary trying to fathom why Node developers support fully optional function arguments, right up to the 4th and 5th argument.

    That all said, the pain of working out all those pieces is worth it, I just wish the transition was easier. I really have enjoyed learning Node and may not go back to PHP. But you aren’t going to see the big PHP apps (phpBB, Magento, Joomla, WordPress et al) converting soon until Node is widely available on share hosts.

  7. Great job! This is so far the best article to compare PHP and Node.js.

    As a long time PHP/MySQL developer and ran a complicate PHP application, I ran into performance issues and hosting issues. My old application with CodeIgniter framework is no longer support in PHP5 and my VPS.

    Instead of learning a new PHP framework, I am amazed by Node.js + Express.js + Angular.js and + Bootstrap combination. I may also get MangoDB in my big picture to become MEAN Stack.

    Thank you for the article. It just make me a believer of Node.js

  8. “I am keeping a close eye on Node.js and I am interested in doing more with it. That said, articles like this are doing a huge disservice to the readers”, why? A lot of people found this article useful, just because you like PHP and don’t use Node.js doesn’t mean this article does a disservice to someone.

  9. I am keeping a close eye on Node.js and I am interested in doing more with it. That said, articles like this are doing a huge disservice to the readers.

    PHP is not going away anytime soon. What this post (and many posts like it) ignores is the rapid evolvement of PHP as a language and the PHP community as a whole.

    I believe that PHP 5.3 (now deprecated) was a game changer and 5.4, 5.5, and the new 5.6 beta continue to build on it’s success.

    I’m doing a lot of PHP development (mostly with PHP 5.4 and 5.5). Frankly programming with PHP 5.2 was boring and dare I say, ugly. PHP 5.3+ gets me excited about programming in PHP again. It’s extremely powerful and many of the objections raised about PHP no longer apply.

    Composer is also brilliant and even holdouts to PEAR like the author of PHPUnit have admitted that it is powerful and useful. I get tired of articles slamming PHP by those who haven’t used it in more than two years and just want to justify their current choices. Take a look at what’s happening now!

    I do concede that PHP is IO-blocking. It’s an entirely different paradigm than javascript. But in regards to speed, PHP is not shabby. Each new release of core PHP is faster than the one before and with the advent of HHVM and HippyVM, you’d be amazed at how fast it can go.

  10. Pingback: PHP vs. Node.js
  11. I really appreciate you taking the time to put together this side by side comparison. Its sure to stir up something, as demonstrated by the ‘my favorite is better than yours’ comments, but it was cool to see the basic PHP I have relied on for ever next to node equivalents.

    You also really hit the nail on the head with the downsides of PHP. The low barrier of entry and general community support of the PHP world has encouraged a lot of barely beginner programmers to contribute to OS projects, creating some terrible code with ‘this is how i think it works’ documentation. I just hope that as node grows it doesn’t encourage the same sort of things.

  12. Yes, Ruby on Rails and Django are frameworks, but this fact doesn’t make them non-alternatives when it comes to web development. In other words, when someone faced with a choice they can choice between a framework and non-framework (just a platform/language).

    PS: You don’t have to take anything seriously if you don’t want to. ;-)

  13. It’s kinda hard to take seriously some one who says things like:
    “There are many better alternatives to PHP, e.g., Ruby on Rails and Django”
    PHP is a language but other two are frameworks…

  14. PHP is a great language and it’s has more mature framework and libraries than any web programming languages out there.. Yes node.js maybe has some good features but who knows what features will be available in the future.Take a look at Hack programming language ,HHVM. It already implemented on facebook.

    I personally like node.js and it’s approaches, but for real production i definitely choose PHP.

  15. node.js v PHP is like comparing apples to oranges.

    node.js is a COMPLETELY different LANGUAGE for one. And second, a COMPLETELY different coding style.

    PHP is C like (with classes, procedural style)
    JavaScript is Event Driven built in, has a Completely different notion when it comes to creating Classes and inheritance and OOP in general.

    I think what scared PHP programmers the most about node.js is that it is a REAL and TRUE possible replacement not for just PHP… but for rapid applications development, period.

    JavaScript progammers of the browser will not need to learn another language… this in the corporate business world is a MAJOR plus, because that is just the way they think.

    I think that PHP’s days are numbered. Not because I want it to be… oh no.. I have 10+ years invested with PHP. And now all these ‘new jobs’ are calling for node.js and angular and all this javascript! Which means having to RELEARN and throw away PHP.

    I think node.js scares PHP programmers because it has some SERIOUSLY good things going for it, as I mentioned above.

    But, there is a LOT of PHP code out there… and javaScript is a wonderful language. But, there is going to be a learning curve in terms of the prototype for class creation and the Event Driven Model… I think that if you want to keep up with the world of web programming… ALL PHP programmers had better take node.js and javascript invasion ( and it is an invasion ) seriously.

    PHP programmers better at least look into creating express apps, socket.io and learn some JavaScript.. after all it will make you good on the Front end in the Browser too.

    This is what I fear. I fear that Corporate is going to want it ALL from the node.js invasion.. they are going to want that one Guru PHP programmer to ALSO be a kick ass jQuery/Angular Front end programmer… and that means design and styling and all that.

    IMHO that is a lot to ask for, in one person. Just because javaScript is the same language that runs the browser logic, can now run the server logic, does not make you adept and therefore REQUIRED to do BOTH.

    What do you guys think? node.js is growing, and is going to really kick PHP’s ass, in due time… but like I said there is plenty of PHP code out there, so use this time you PHP programmers to get to know node.js and JavaScript server side while you have spare time..

    The node.js flood is upon all PHP programmers, whether you like it or not. Dont, mean PHP will die anytime soon. Nginx (is event driven) and with php-fpm still gives node.js a run for its CPU cycles.

  16. To declare a new object in Node.js:

    var bar = {}; // or new Object();

    To declare a instance of a class: (that’s what php do with the class syntax)

    var foo = function () {
    return this;
    };
    foo.do_foo: function () {console.log('Doing foo');}

    var bar = new foo();
    bar.do_foo();

  17. To declare a new object in Node.js:
    “`
    var bar = {}; // or new Object();
    “`

    To declare a instance of a class: (that’s what php do with the class syntax)
    “`
    var foo = function () {
    return this;
    };
    foo.do_foo: function () {console.log(‘Doing foo’);}

    var bar = new foo();
    bar.do_foo();
    “`

  18. Hi

    thanks for article, and especially thanks for comments!

    I need to start a new project and I am not sure if start with PHP or nodejs.

    The main problem is learning curve, since I am PHP developer, and just start learn nodejs world.

    I love the real time feature of nodejs, and I would like to know by someone here what think about PHP solution for “Event-driven, non-blocking I/O with PHP” http://reactphp.org/

    @Luciano Mammino I like your comment, but you said:
    “At the moment the greatest hole that remains uncovered (that privileges Node.js) is about real time applications development.”

    reactphp can be a solution for this?

    I would like continue my work on PHP, but it’s not first time that I hear about not secure future of LAMP stack, and speak about nodejs as future.

    Why facebook and many other main site are not in nodejs but in PHP? Because nodejs exist just 3 years.

    If nodejs exist since PHP start, which will be the most used technologies now day?

    I think the most accurate comments (and most near the true) is by @Luciano which resume it last phrase:

    “Definitely I feel that Node will keep stealing part of PHP market in the next years but I am pretty sure the two languages will coexist without great hurdles.”

    Thanks!!

  19. Hello!
    I came here via Google (this page has a good SEO though) after I recently suggested by my fellow friend about node.js.
    I heard it quite a long time ago but I didn’t sure what is it. But today, after reaching your website, I found your comparison between PHP and Node.js is horribly unfair.
    Even that in your post you are praising Node.js so much, but to me, it seems like php is somewhat better. I am not challenging you for any of debates or some sort, but this is just in my opinion.
    I am not a great programmer yet, I sure know that. However, since Node.js seems to be hard to be learnt, and based on other people’s comments, I think I would rather stay using PHP due to its bright future.
    No offense to the Node.js. I believe any programming languages should live as long as it suits every programmer :)

    thanks for the post.

  20. First of all, I was a PHP programmer. I do .net programs recently. All I concern is not the difference of syntax, but the scalerbility. In large projects we are not much aware of the lines of code. The most important thing is to modulize works and assign to team members.

    I came here is due to the event driven feature of Node.js. which I think Node.js is worth to take a look into. Event driven is hard to handle for squence style programmers. But it reacts more similar to real world.

    Besides, Is there any print services suitable for Node.js? please let me know if any

  21. I have to disagree. NodeJS is perfect for high throughput problem-solving, but it is unsuitable for larger projects, simply because js is an prototype based language.
    That being said, NodeJS _is_ faster in many ways, but one of the largest sites in the world (aka facebook) run a major part of their code in PHP. From your complex project I can see, that there is no OOP whatsoever and no framework has been used whatever so I highly have to doubt your high aspirated critizism.

    And just on a side note, all-in-one solutions are never as good as a mixture of technologies, simply because the specialization is missing.

  22. Pingback: node.js intro
  23. Interresting analysis, but as you said, i think you are completly biased and there are few things more to take in considaration;)
    One thing to take into consideration when choosing your langage is the pool of CAPABLE developpers (in opposition to “wanna be” ones) and there without any surprise PHP is still far ahead.
    Another point coming strait from the previous one is the cost of the technology, not by itself, but all together, and there once again, PHP wins (more devs, mean, less expensive at same experience/quality level). Same for system administrator (if needed) loads of them are really experemented on LAMP systems
    You also have to think about evolutivity and maintainance (i know PHP is pretty good on that with lots of security patches for older versions but i don’t know for node)

    i’ll finish by a sentence i heard (i don’t remember who, or the exacte phrasing but it was something like) :
    Javascript is like a pornstar, you can lots of things with it, but at some point, it’s gonna get dirty

    PS: Good lord, would you mind using foreach loop (as said a previous comment), they are so much more efficient to loop on an iterable variable that they should remove for from the language…;)

  24. Hi Paulo,

    That’s right, Django and Ruby on Rails are frameworks. However, there is no mistake here, because they are all alternatives to each other (some better, some not).

  25. “There are many better alternatives to PHP, e.g., Ruby on Rails and Django”

    You mean Python. Django is a framework.

  26. Sure, there are multiple ways to iterate over an array. The snippets above are just for illustration due to the fact that the comprehensive language comparison is the topic for another vast article in itself.

    It tends to be that web development is moving toward generalism. In addition to that 99% of startups for whom the question “PHP vs. Node.js” is important have only one or two developers.

    It’s pointless to write comparison articles for big companies, because let’s be honest, most of the time you work with what you have to work. :-)

  27. A couple of points of critique :

    As of 5.4 you can also use the short array syntax in PHP, which replaces array() with [].

    Why aren’t you just using foreach in your PHP array itteration? Your code will be a lot less cluttered.

    Depending on how large the company is you work for, you may not even have to switch between front and backend context because they belong to separate developers or teams even. So yeah.

    The same goes for having to learn two extra languages… Odds are that if your company is more than a few developers big there an mysql expert or DBA, or that your DB is abstracted away by Doctrine or another framework savong you the hassle of having to write queries yourself. Apache ditto.

    Having said that, being able to use (parts of) the same code in both the browser and the server is a big advantage of node.js, although I personally prefer CouchDb for this.

    Maybe CouchDb versus Node.js could be next? :-)

  28. Nice post. But, I think the huge propagation of Node.js is very dependent of the NoSQL paradigm.
    Because most applications in someway needs a very reliable databases, and NoSQL isn’t widely used.
    As a PHP programmer, I must to recognize the fascinating and simple characteristics of Node, and I really hope that it grows quickly.

    Thanks for sharing knowledge!

  29. “There are many better alternatives to PHP, e.g., Ruby on Rails and Django”

    Why do you compare programming languages to frameworks? You should rather comapre Symfony2 to Django.

  30. Hi Azat,
    I really enjoyed your post and your comparison of PHP and Node.js.
    I’m a PHP developer with several years of experience. I also had time to work with Java, VB.net, Javascript, Python and Ruby, but my language of choice remains PHP.
    I do agree with many points in your analisys, but I don’t think PHP is such an obsolete language and even more that it’s going to disappear. I don’t want to criticize your point of view because I’m not so experienced with Node.js and probably I can see only one side of the comparison.
    I admit PHP was such a mess few years ago, especially if compared with language such as Java and Ruby (and their great tools and frameworks). Anyway the PHP community has several great developers and they probably felt something has to be done to make PHP a better language, up to date with current needs.
    So many good projects came to life: PHPSpec, PHPCS, phpmd, pdepend, Behat, Mink, Boris, Composer, Symfony2 components, Doctrine2, Twig and so on (I know, I mixed totally different tools and libraries, but I just wanted to point out the amount of good projects that has been produced by the PHP community in the last 2/3 years). Furthermore frameworks like Symfony2 and Zend Framework2 (and their whole community) heavily encourages OOP and its best practices. With PHP 5.3 and PHP 5.4 the language also improved its OOP features with namespaces and traits.
    That’s just to say that PHP has still a solid base and it’s improving everyday. It has many defects but also a great community providing great tools to fix them.
    At the moment the greatest hole that remains uncovered (that privileges Node.js) is about real time applications development.
    Definitely I feel that Node will keep stealing part of PHP market in the next years but I am pretty sure the two languages will coexist without great hurdles.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.