PHP to Node.js: When Migrating is the Right Idea and How to Do It

PHP and JavaScript used to go hand-in-hand, with JavaScript working the browser while PHP handled server-side tasks. Since Node.js came along, however, there’s been a battle brewing for developer mindshare. In truth, it’s not that simple. Both platforms have strengths and weaknesses. For some purposes PHP is the better tool, but sometimes Node.js has more to offer a particular project. Read on to find out what each does best, when it’s the right move to migrate to Node.js, and how to do it.

PHP Basics

PHP is a declarative, general use scripting language used for server-side development. It was created in 1994 and used to build the original WordPress as well as both Joomla and Drupal. Despite its age, PHP is currently the most preferred language for server-side processing. 83.4% of all websites whose code is known use at least some PHP. The appeal is due partly to its low cost. All PHP features and updates are open source and free. On top of that, the language is flexible and encourages innovation. Because PHP interprets requests on the server-side, it allows for more interactive features than simple HTML. php-websites

Strengths

There’s a reason over three quarters of the internet uses PHP. It was designed for the web, is easy to embed into HTML, and has a deep code base. Developers can use it to create blogs and websites with dynamic features in a very short time. One of PHP’s core strengths is powering database-enabled websites that can be used by non-technical employees. A CMS built with PHP and MySQL, for example, is intuitive enough that anyone can update content and do basic management tasks after a simple tutorial. PHP has stood the test of time. It is mature and portable, able to run on nearly any platform. The language has proven its reliability for server-side work again and again. When there is a problem, PHP enjoys a huge support community. Developers can easily find help troubleshooting unexpected issues or brainstorming workaround for tricky situations. Finally, PHP has a low barrier to entry. Its syntax is similar to C, making it easy to learn, and it’s more forgiving of mistakes than many languages. Errors kill the specific thread, not the whole process. That means even “spaghetti” code will run around mistakes.

Weaknesses

Maturity is an asset, but it can be a drawback as well. PHP’s age means there are many outdated plugins around that can create lag or introduce weaknesses into a system. It’s important to check any new plugins thoroughly to be sure they’re still supported. PHP has an issue with separation of concerns. The “Model-View-Controller” (MVC) pattern- a best practice for scalable web development- separates the logical components of an application: data, behavior and representation. This ensures lasting readability, maintainability, and scalability of web applications. PHP, however, tends to mix HTML and language syntax inside HTML files. Views and business logic aren’t separated, which is hard to read (let alone maintain). Applications with a large code base become incredibly labor-intensive to maintain. Also, because of the muddled logic it’s difficult to extend PHP applications with new functionalities. Finally, the declarative style of PHP can stand in the way of creating as a team. Flexibility makes for bulky code when multiple people are involved. Commands can be written anywhere, so one person’s additions might prove tricky for other developers to find and detect. This presents an issue when adding new members to the maintenance team.

Node.js

Node.js is a runtime environment which uses JavaScript for server-side application development. The main selling point of Node.js is that it enables full-stack JavaScript usage. It was first written by Ryan Dahl after he became frustrated with the limitations of existing web servers. He set out to find a better solution, ultimately creating the first version of Node.js in 2009. nodejs-website

Strengths

Though it’s a newcomer compared to PHP, Node.js is growing fast in popularity. It powers half a million websites and rising, with business and industry heavily represented in that number. There’s an energized community of developers behind Node.js and new modules are being released all the time. The opportunity for a unified stack language draws developers to experiment with Node.js. Having JavaScript throughout improves the reusability of code. Front and back end developers can coordinate seamlessly when using the same language, leading to faster, more efficient development and lower costs. The resulting code is easier to maintain, too. Besides being easy, Node.js offers high performance. It has continuous server connections, a shorter request processing chain, and a faster engine in the Chrome V8 Virtual Engine. Switching to Node.js doesn’t come with a significant drop in flexibility. It’s an unopinionated framework, with no hard dependencies or strict conventions developers must follow. Most interesting for growth-oriented companies, Node.js is highly scalable. Its event-driven architecture features built-in asynchronous processing. The non-blocking IO model lowers the load on individual processors and allows it to handle more requests than multithreaded solutions. Module caching furthers the tool’s scalability. Modules are downloaded and initialized when they are called for the first time. Afterwards they remain constantly available for later use.

Weaknesses

Being single-threaded and event based means Node.js isn’t well-equipped for CPU-intensive processes. It runs into trouble handling graphics editing and creation, audiovisual editing, data structure transformations, complex calculations (for example, HTML template rendering), zipping and unzipping, and managing concurrent requests. Node.js is relatively new. Less maturity comes with a cost: though the community is large and active, it can be hard to assess the quality of individual modules. There isn’t good oversight for approving module publishing, so developers must make a point of checking prospective modules for bug fixes, updates, and other signs that it’s still being maintained.

When to Switch

Node.js is exciting, but not everyone should start planning to migrate. There are good reasons to stay with PHP.
  • The application features CPU-intensive processes.Node.js isn’t designed to handle these.
  • A virtual server with Secure Shell (SSH) access is needed to run Node.js applications.When that resource isn’t available or desired, Node.js isn’t an option.
  • PHP is easier to integrate and deploy.When so many websites already use PHP, there’s less fear of incompatibility. Plus, non-technical employees can update and maintain content through the CMS.
  • The project involves working with relational databases.This is part of PHP’s original purpose, so there are many simple tools for interacting with an RDBMS. Node.js does have tools for this purpose, but they aren’t as simple or elegant.
With all those arguments in favor of PHP, what can be gained with Node.js? The unified stack language is exciting, but one feature stands out as the cause for its growing popularity: The Node Package Manager. It’s the largest package registry in the world, with over 350,000 packages at the time of print. For perspective, that’s more than the entire Perl CPAN repository collected over more than 20 years. The NPM is very active. Every week 160 people uploaded their first package to the registry, and users install as many as 18 billion packages a month. This vibrant and comprehensive resource is a major benefit for developers. It reduces development time spent on tedious general tasks, freeing developers to focus on specific functions and making their code easier to maintain. There is something similar for PHP called Composer. It has a large amount of useful modules, but it doesn’t come standard and isn’t as comprehensive or active as the Node Package Manager. All things considered, the best uses of Node.js include:
  • Real-time Applications: Chats, collaboration programs, Single Page Applications(SPAs)
  • Data-intensive applications:Internet of Things (IoT)
  • Rapid development of highly scalable applications

Best Practices for Migration to Node.js

As with any migration, making the switch to Node.js involves some measure of disruption. Following these best practices will make the transition as smooth as possible.

Plan onboarding carefully

Preparing staff is as important as preparing the data. Provide group training resources that account for the varying levels of skill team members may have with JavaScript and Node.js. Set up pre-migration training to get everyone on the same page. This should include JavaScript concepts like asynchronous programming, scope, data types, function arguments, function & objects in JavaScript, and callbacks. Identify employees who might need additional support or mentoring.

Start with smaller apps

Choose a good team to handle early stages of the transition. Their success serves several purposes. It proves the viability of Node.js, gains support for the process, and gives other teams the confidence to follow suit when it’s their turn.

Implement a module screening process

Earlier it was mentioned that 160 developers publish their first module to the NPM every week. While a promising sign of activity and innovation, that does translate to some uncertainty regarding module quality. There could be serious bugs that haven’t been seen yet or even malicious code designed to be overlooked on a cursory inspection. Have strict procedures in place for using new modules. Either choose well-tested, popular modules with good ratings or go through the code of more obscure modules to make sure they don’t pose a threat.

Standardize integration

Existing systems are often complex and require set-up to integrate. Because Node.js is highly flexible, teams can invent different solutions to the same problems. This makes connecting components and working seamlessly as a team harder than it needs to be. Standardizing integration practices cuts down on that complexity and encourages smoother team operations.

Lock dependencies

Relying on servers to pick up dependency patches can also introduce unwanted changes. Use shrink wrap and lock features to increase consistency and control over updates. Debugging is easier when it’s simple to see which changes came from which dependency.

Emphasize Node.js best practices

While Node.js is new, it’s not so new that there aren’t well-established practices for achieving the best results. For instance:
  • Adopt a consistent style guide.
  • Utilize environment variables from the start.
  • Automatically restart the app after a runtime error.
  • Load and configure dependencies up front.
  • Keep code compact to reduce lag and increase speed.

Looking to the Future

When WordPress announced they were shifting focus from PHP to Node.js in 2015, many suggested it was the “end of PHP”. There was some evidence that this was more than hype. Calypso was written entirely in JavaScript using Node.js and React. Since WordPress accounts for a quarter of the world’s largest sites and 59% of all sites, this seemed to represent a major hit to PHP’s popularity. However, updates like PHP 7.0 and Hack/HHVM have added more functionality to PHP. With several of the more pressing issues address by these updates, some developers feel there isn’t enough potential gain to migrate to Node.js. There’s also an argument in developer circles that Node.js is too constantly new to adopt. It remains to be seen whether either will take dominance or whether something wholly new will overshadow both. For now, PHP is a safe choice for many projects- but Node.js is positioned to grow as companies become more interested on scalability and IoT.

Is Node.js a good fit for your next application? Concepta’s developers can walk you through the pros and cons and put together a development plan that puts your business goals first. Set up a free consultation to get started!

Request a Consultation