Preface

Why bother with this book?

PHP is an old language, as Internet languages go, invented in 1995. Node.js is new, very new, invented in 2009. Looking at PHP side by side with Node.js gives you a bird’s eye view of where web servers started, how far they have come, and what’s changed. But, more importantly, it shows what hasn’t changed—what the industry as a whole has agreed are good practices—and a little bit of what the future holds.

The biggest difference between PHP and Node.js is that PHP is a blocking language, relying on APIs that don’t return until they are done, and Node.js is a nonblocking language, relying on APIs that use events and callbacks when they are done. But, except for that, they are surprisingly similar. Both use the curly bracket notation ( { and } ) for blocks of code, just like the C programming language. Both have the function keyword, which serves the exact same purpose and has the exact same syntax in both languages. If Node.js shows that blocking APIs are the past, it also shows that a pretty specific variation of the C programming language is the past, present, and future. Callbacks may be an evolution, but syntax is almost frozen.

But beyond just, “oh, isn’t that interesting,” why bother with this book?

PHP is supported by a zillion cPanel website hosting services. If you develop a web application and want to give it to other people to run, they can install it almost anywhere if it is written in PHP. They can buy web hosting for $10 per month, install your PHP web application, and be on their way.

Node.js is not supported by a zillion cPanel website hosting services. In fact, I don’t know even one web hosting service that supports it. But I know that a lot of developers are interested in it and are writing Node.js code. By writing Node.js code, you make your web application code interesting and useful to a lot of developers. If you develop a web application and want to give it to other developers to improve and reuse, they can get your Node.js web application from GitHub or wherever else the source code is hosted.

In a perfect world, you could appeal to both sets of people.

Ours isn’t a perfect world, but you can still achieve this goal by porting your PHP code to Node.js code and simultaneously having and developing two working codebases in two different languages.

The Mission

The mission of this book—and when I write “mission,” I mean it in the “I really, really, really, really want you to do it” kind of mission—is to convince you to convert some of your PHP code to Node.js code. I don’t want you to just read this book. I want you to actually sit down at a computer and take some of your most tired, annoying PHP 4 code and convert it to Node.js using this book as a guide. I want you to see for yourself that PHP and Node.js are not that different. I want you to see for yourself that your PHP code does not need to be thrown away and rewritten in Node.js from scratch. I want you to see for yourself that you don’t have to surrender to just living with your PHP code, being a prisoner of the past.

As you will see, converting your PHP code to Node.js code isn’t just about Node.js. It is also about improving your PHP code. An important step throughout this book is refactoring and improving your PHP code such that it is easier to convert it to Node.js code. This book isn’t just about making a new Node.js codebase. It is about improving your PHP codebase and creating a new Node.js codebase. It is about both codebases: your PHP codebase and your Node.js codebase. Converting your PHP codebase to Node.js can make you a better PHP developer.

If you are a PHP developer, this book is perfect for you because you can learn how to develop Node.js code by using your existing PHP knowledge. You can see how certain code works in PHP, such as reading a text file, and in the next few paragraphs, you can see how exactly the same thing is accomplished in Node.js. Unlike other Node.js books, this book does not describe file handling in general. It specifically compares it to PHP so you can see the nuts and bolts of what it looks like in the language that you know as well as in the language you are learning. You might even find a few corners of PHP you weren’t previously aware of, because a few of those PHP corners are central concepts in Node.js.

If you are a Node.js developer already, you have a decent chance of learning PHP from this book. After all, if PHP developers can figure out Node.js by looking at PHP code side by side with Node.js, there is good reason to think that Node.js developers can figure out PHP by looking at the same code. Even better, by comparing Node.js to a specific different language, such as PHP, it will give you a good idea as to how much of Node.js is the same as PHP.

Comparing two languages or, even better, showing how to convert or port from one language to another, is a powerful way to become an expert in both languages. Other books, which deal with only one language, mostly read like step-by-step tutorials or encyclopedias. “This is this,” they read, “that is that.” They can describe concepts only as abstractions. Other books can’t use the powerful explanation of an ongoing comparison of two languages that this book does.

Besides being more effective, a book such as this one can also be more interesting and focus on only the interesting topics. In a run-of-the-mill Node.js programming book, time is spent explaining what a statement is and why every Node.js statement ends in a semicolon (;). That’s dull. But when a book is explaining how to program in Node.js in a vacuum without any point of reference (such as the PHP language), there is no alternative. With this book, I can assume that you already know what a PHP statement is and that a PHP statement ends in a semicolon (;). All that needs to be said is that Node.js is exactly the same way. With this book, I can assume that the reader has a specific background—PHP development—instead of needing to write more broadly for people who come with a Python or Microsoft Office macro background.

By proselytizing the conversion of PHP code to Node.js code, I am not saying that PHP code is bad. In fact, I think PHP is a very capable and pretty good language. I am not saying that you should convert your PHP code to Node.js code and then throw away the original PHP code. I am encouraging you to keep the original PHP code and improve it while, at the same time, becoming a skilled Node.js developer. PHP and Node.js are both important.

When first setting out to write this book, I made a very important decision early on: I was going to focus on real-life, practical, existing PHP code. PHP 5 is the current PHP version, but there is still a lot of PHP 4 code out there. This book has explicitly avoided the easy prescription: convert your PHP 4 code to PHP 5 code, then use this book to convert your PHP 5 code to Node.js. No, despite the fact that PHP 4 support is rapidly fading in favor of PHP 5 support, this book takes the much harder road of showing how PHP 4 code can be improved upon and converted to Node.js code without requiring PHP 5 features. Although this book does show how to convert PHP 5 code to Node.js, let me assure you that PHP 4 code is readily convertible to Node.js using this book.

Very soon after making the decision to embrace and address PHP 4 code, I made another decision related to this book: I was going to describe a system of conversion such that the PHP code and the Node.js code would be kept synchronized and working throughout the conversion process. At the end of the conversion process, both the PHP and Node.js codebases would be fully functional and, going forward, new features and bug fixes could be developed on both codebases simultaneously. This decision avoids a much easier approach, which would have been a “convert-and-discard” conversion process where the PHP codebase would be unsynchronized and possibly not working at the end of the conversion process and the developer’s only option would be to proceed ahead with the Node.js codebase by itself. This would have made a much shorter book, but would have been a cheap trick—a way to make life easier for me, as the writer, and make the book less useful to you, as the reader.

These two decisions, one to support PHP 4 and the other to support two synchronized PHP and Node.js codebases as an end product, have made this book longer than it would otherwise be, but have also made it eminently practical. This is not a book that you will read once and put on the shelf as an “isn’t that nice to know” book. This is a book that you can use for reference to quickly refresh yourself about important aspects of either PHP or Node.js.

By now, you might understand what the mission is and why it might be worthwhile. But maybe you are still doubtful.

Consider the following PHP code, which was taken from a real-world PHP web application that implemented instant message−style chatting:

function roomlist() {
  $rooms = array();
  $room_list = mysql_query(
    'SELECT room FROM '.SQL_PREFIX.'chats GROUP BY room ORDER BY room ASC'
  );
  while ($row = mysql_fetch_assoc($room_list)) {
    $room = $row['room'];
    $rooms[] = $room;
  }
  print json_encode($r);
}

Now consider the equivalent code in Node.js:

function roomlist() {
  var rooms = [ ];
  link.query(
    'SELECT room FROM '+SQL_PREFIX+'chats GROUP BY room ORDER BY room ASC',
    function(err, rows, fields) {
      for (var r=0; r < rows.length; ++r) {
        var row = rows[r];
        var room = row['room'];
        rooms.push(room);
      }
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end(JSON.stringify(r));
    }
  });
};

Sure, the syntax is a bit different. To concatenate strings, PHP uses the dot (.) operator whereas JavaScript uses the plus (+) operator. PHP uses array() to initialize an array, but JavaScript uses square brackets ( [ and ] ). It’s not identical.

But for heaven’s sake, it’s still pretty darn close. This isn’t “fake” code, either: it uses arrays, accesses a MySQL database, uses JSON, and writes output.

The similarities and the possibility of converting PHP source code to Node.js, and consequently the writing of this book for O’Reilly Media, are a direct result of my experience with creating a Node.js implementation of my open source project.

Who I Am

I’m Daniel Howard, the founder and sole maintainer of ajaximrpg, a preeminent browser-based instant messaging (IM) and chat system. ajaximrpg is specifically geared toward playing tabletop role-playing games, such as Dungeons & Dragons, over the Internet, although the role-playing specific features can be stripped away to reveal a general-purpose client. ajaximrpg is completely open source and available via SourceForge with a full range of supporting services such as a Twitter feed, a Google Group, and a live demo.

ajaximrpg was originally written in PHP 4 with no inkling that it might someday be ported to Node.js JavaScript. But it works on PHP 5 and, now, on Node.js.

Starting in January 2012, it took me a single week to come up to speed on Node.js and do a proof of concept to have my client-side JavaScript code detect the installation status of the server side running on Node.js. In a month, I had enough of a few thousand lines converted to enable users to log in and IM each other. It dawned on me that there were general principles at work here, and that these general principles could be laid out in a book to explain how to convert any PHP source code to Node.js and, using these principles, the reader of the book could apply them to his PHP source code much quicker and more accurately than just muddling along as I had.

I put aside my mostly working but not yet completed Node.js implementation and immediately set out to write this book that you now hold in your hands (or view on your screen).

This Book

This book consists of 12 chapters, starting out with the basics and moving on to more advanced topics.

Chapter 1, Node.js Basics

This chapter describes how to install Node.js and use the Node.js executables, node and npm. It also describes how to install the Eclipse PDT and configure it for use for a PHP to Node.js conversion.

Chapter 2, A Simple Node.js Framework
This chapter presents a simple Node.js framework such that individual PHP pages can be converted to Node.js files and the resulting Node.js files will be invoked when actions, such as visiting a URL, are taken against the Node.js web server.
Chapter 3, Simple Callbacks
This chapter explains how to refactor blocking PHP source code such that it can be easily converted to nonblocking Node.js source code that uses callbacks. It presents the concept of linearity as a simple way to analyze and improve PHP source code such that it can be placed in Node.js callbacks when converted to Node.js.
Chapter 4, Advanced Callbacks
This chapter presents a more sophisticated and generic way to refactor blocking PHP 4 source code to simulate anonymous functions, function variables, and closure. For PHP 5 source code, it explains how to use PHP 5 features to actually implement anonymous functions, function variables, and closure.
Chapter 5, HTTP Responses
This chapter explains how to convert PHP output, such as the print and echo keywords, into HTTP responses in Node.js.
Chapter 6, Syntax
This chapter explains how to convert PHP syntax, such as concatenating two strings, into Node.js syntax.
Chapter 7, Variables
This chapter explains how to convert PHP single and array variables into Node.js, as well as common operations, such as adding and deleting elements from array variables. It also describes how to convert PHP types to Node.js types.
Chapter 8, Classes
This chapter presents a way to implement PHP classes and class inheritance in Node.js with a step-by-step technique to perform the conversion.
Chapter 9, File Access
This chapter explains all the file reading and file writing APIs in both PHP and Node.js. It explains how to convert the PHP file handling APIs into their Node.js equivalents.
Chapter 10, MySQL Access
This chapter describes all the ways that a database, specifically a MySQL database, can be used in a web application. It provides a step-by-step procedure for converting database access code from the PHP MySQL APIs to use the node-mysql Node.js npm package.
Chapter 11, Plain Text, JSON, and XML
This chapter explains three data formats: plain text, JSON, and XML. It explains how to convert PHP source code that uses PHP JSON or XML APIs into Node.js source code that uses similar Node.js npm packages.
Chapter 12, Miscellaneous Functions
This chapter provides Node.js implementations for a large number of PHP API functions. These Node.js implementations can be used to speed along conversion and provide an interesting way to contrast PHP and Node.js.

Now let’s get started with Node.js.

About This Book

This book is about how to take existing PHP source code and develop new Node.js source code from it. PHP and Node.js have many similarities, but of course, there are some significant differences. By leveraging the similarities and noting the differences, you can use your PHP experience to learn Node.js and, ultimately, create a Node.js web application that is a drop-in replacement for any existing PHP web application that you have.

This book assumes that you are a developer who understands the basics of development, such as creating and then implementing a design in working lines of programming code. It assumes that you are already familiar with classes, functions, and looping constructs. It also assumes that you are familiar with web development, including the basics of how web browsers and web servers interact to create a web application.

Furthermore, this book assumes that you have significant expertise in the PHP programming language. If you do not have a background in the PHP programming language, it is possible that you can use your background in another programming language (e.g., Python, Ruby, or C) and, by reading this book and examining the intersection between PHP, Node.js, and the programming language that is familiar to you, acquire a good understanding of both PHP and Node.js. Not necessarily easy, but possible.

This book can be read straight through as a Node.js tutorial, consulted as a reference to see how a specific PHP feature can be implemented in Node.js, or executed as a step-by-step recipe to convert an arbitrary PHP web application into a Node.js web application. The book was written to serve all these purposes.

No matter how you approach this book, as its author, I sincerely hope that it answers the questions you have about PHP and Node.js.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This icon signifies a tip, suggestion, or general note.

Caution

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Node.js for PHP Developers by Daniel Howard (O’Reilly). Copyright 2013 Daniel Howard, 978-0-596-33360-7.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Safari® Books Online

Note

Safari Books Online (www.safaribooksonline.com) is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens more. For more information about Safari Books Online, visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/nodejs-php. To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

This book is the product of many months of effort by me, of course, but also by several others.

I want to thank the editors at O’Reilly Media, Inc., specifically Simon St. Laurent and Meghan Blanchette, for their encouragement and feedback.

I want to thank Neha Utkur, the book’s technical editor, for her enthusiasm and willingness to provide feedback on a whole range of areas that sorely needed her input. Her contribution has made this a much better book.

Finally, I want to thank Shelley Powers for lending a second pair of eyes to review the book for technical accuracy.

Get Node.js for PHP Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.