DEV Community

Node vs PHP

Aleksey Razbakov on December 23, 2019

Is anyone here prefers Node over PHP for Backend?

Collapse
 
haikelfazzani profile image
Haikel Fazzani

Node.js is a JavaScript runtime and PHP is language !! PHP vs Javascript or you can compare Nodejs vs Zend Engine. be productive and avoid comparing languages .. all languages are good ...

Collapse
 
razbakov profile image
Aleksey Razbakov

My question is not about language, but about Server-Side Environment. How would you let your server handle request?

P.S. Should I put PHP-FPM in original question instead? :D

Collapse
 
andreidascalu profile image
Andrei Dascalu • Edited

You should really make your question clear as to the scope of the expected answer.

You can mention fpm, sure, but fpm is simply the interpreting engine.

As to how to let the server handle requests, it's more about what features you want and whether you have external constraints from other systems in your stack.

Theoretically both node and fpm benefit from a reverse proxy or lb in front of them. The downside of fpm is that it needs a compatible web server as opposed to node.

Fpm only interprets php code, so the proxy in front needs to route those requests for php files and be able to serve non+php directly, unless you want to write a generic we server in PHP (not efficient). Therefore php works with nginx or lighttpd unless you go modphp and use apache with the embedded module (where prefork raises questions on performance VS the multithreaded nature of nginx)

Node has no such constraints. It can work with plain proxies like haproxy or even serve requests straight up (but you would need to pay attention to stuff like security).

In a containerized environment, php shows some limitations in that nginx +fpm is a bit of a pain to setup efficiently (think kubernetes) and you end up using roughly 3 lb's in front of fpm, nevermind the inherent networking overhead (usually I go with apache there)

Node is easier from this perspective, but switching ecosystems coming from php is not that easy.

Myself I ended up going with Roadrunner for php, as it is wrapped in a very efficient golang server + enforces psr compliant requestd/responses

Thread Thread
 
razbakov profile image
Aleksey Razbakov

If you would start a new project, what would you make as your backend? Node or PHP? Express or Laravel? Let's say you write a REST API, what stack would you use and why?

Thread Thread
 
andreidascalu profile image
Andrei Dascalu

I would make my decision based on the goal. For example I have projects that leave a lot of room for learning. I would go with express in this case just to improve my knowledge, but I would also use it in cases where node packages may be superior to php (in case of grpc for example)

Otherwise I would use php but I would not use any of the major frameworks (I have a performance comparison of returning 100k json encoded rows from two related tables, Laravel is the worst performer of all).
I would favor a microservices framework like Swoole if I weren't inclined to make a monolithic API. Otherwise I would use a microframework like Symlex but nowadays I sort of favor a custom solution built around a fast router (there's nikic but also the phpleague router). For an API there aren't many requirements: fast router with Middleware support, DI container (phpdi is excellent) and maybe doctrine for a strong orm with several layers of caching. Of course, logging and some metrics/observability would be nice.
I have a sort of personal 'framework' that rivals symfony 5 in performance but it still lags behind the likes of ubiquity 2 and symlex.
But my main requirement from a php stack would be to handle routing for psr requests and responses and neither symfony nor laravel do that.
This comes from the fact that nowadays I consider it mandatory for a php api to be deployable with roadrunner (symlex is built for roadrunner compatibility), in this case php blows node/express out of the water and can close in on rust performance for example.

Thread Thread
 
tracker1 profile image
Michael J. Ryan

I wouldn't use either for grpc... If you're interested in container orchestration like kubernetes, I might use node for it. You can't use grpc+cluster modules together iirc.

Collapse
 
xroal profile image
Roman Stejskal

Node all the way.

JavaScript syntax is much nicer than PHP, also more concise, and actually OO. JavaScript doesn't need special handling of UTF-8, unlike PHP, where my scripts very much like to save mumble-jumble into the database instead of the actual characters.

Node also has a proper package system, which lack of has bitten my ass many times in PHP (when the official docs tell to you composer install a package but you actually can't because a third dependency of both of them has a version mismatch... Looking at you, Lumen), but never in Node, where each package can require its own version of anything and it just won't clash.

TypeScript.

Also, native JSON support is nice when working with JSON based REST APIs or services in general.

Collapse
 
nerdlyist profile image
Coury Ryan Richards

Composer works great and you can 100% specify versions. Also, composer is the only one which do you prefer npm, bower, yarn... whatever comes next.

Syntax is an opinion. I mean don't get me wrong php could have helped itself with naming and parameter ordering consistency. Some people like ruby and I know cold fusion evangelist.

PHP has type hinting or you could move to Java or .net if you wany types and "actual oop/d".

Json is pretty straightforward with json_encode/json_decode. Where a lot of other languages you need an entire library to make that work on complex objects (no not js).

As for the question. I would say js/node are hot to trot right now. There are a lot of companies willing to pay top dollar for that skill set.

If you are starting a company though php can get all the work done for a fraction of the cost. Php developer (who creat the same systems) are very underpaid.

Also, realize whatever is best right now won't be in 10 years and you should always be evolving your skillset.

Also realize that best is very tricky and depends a lot on what you are doing.

My personal experience is Java, python,php and js. But I've gotten stuff done in ruby, cold fusion and .net.

Server wise node for js seems pretty standard. PHP has Apache mod-php which is well documented. If you are making an API I think php-fpm would be a good alternative although I usually run into issues when it comes to returning static content like images or css files. Still have not found a good solution for that without some hacky methods.

Collapse
 
razbakov profile image
Aleksey Razbakov

JavaScript syntax is much nicer than PHP

Can you please share some nice projects in Node? Do you consider this github.com/HugoDF/express-bull-es6 as a good practice?

I am lacking some abstraction and organization of the code that PHP has.

Collapse
 
xroal profile image
Roman Stejskal

You can take a look at Example Node (Express + Mongoose) codebase containing real world examples.

What I meant specifically by syntax is, e.g.,

  • no $ for variables,
  • object literals { key: value } vs [ 'key' => value ],
  • anonymous functions (args) => retVal vs function (args) use (vars) { return retVal; }

What abstractions and organization of code do you mean?

Collapse
 
tdias25 profile image
Thiago Dias

when people say simple sh*t like this i can't do nothing but wonder what the engineers who made complex frameworks such Symfony and ZEND would say lol

Collapse
 
vlasales profile image
Vlastimil Pospichal

I prefer PHP.

Collapse
 
razbakov profile image
Aleksey Razbakov

Symfony or Laravel?

Collapse
 
vlasales profile image
Vlastimil Pospichal • Edited

Vanilla MVC.

Thread Thread
 
razbakov profile image
Aleksey Razbakov

No frameworks?

Thread Thread
 
vlasales profile image
Vlastimil Pospichal

No frameworks - some thin boilerplates only. PDO for databases, XSLT for templates. Model 55 lines, router 10 lines. Without any HTML inside.

Collapse
 
ttshivhula profile image
Tshivhula Tshilidzi

The question is not clear since you comparing two different things. Assuming you comparing PHP and Javascript. I prefer working with Javascript just because I think it's best to write in one language because in most cases you end up writing Javascript anyway. Php itself is still a solid language!!!

Collapse
 
razbakov profile image
Aleksey Razbakov

Let's say you need to write a newsletter system that would send email to 1k users weekly. Would you write this script in Javascript or PHP? Would you use any framework for that? What would your cronjob look like?

Collapse
 
chrisrichter profile image
chris-richter

I do something like that from firebase using AWS-SES with a nodejs cloud function (like lamda in AWS). I don't use the cloud scheduler for it, but that certainly could be done.

Similar logic lives in other functions that use pubsub for transactional emails and alerts.

The farther I can get away from email tasks and servers, the better. 1,000 emails is $0.10.

Collapse
 
xroal profile image
Roman Stejskal • Edited

Everything in JavaScript is an object, with properties, methods... Try 'string'->length in PHP.

The fact it's using prototypes instead of classes doesn't mean it's not object oriented.

Thread Thread
 
mjhd profile image
mjhd

This is a point of great contention, it really depends on how broadly you define an object, I agree that native classes are a mandate for OOP, which is why PHP is actually object oriented. The question to me is, “is object oriented programming SIGNIFICANTLY different than a custom data structure” - any language can add objects in the abstract, but the point is fidelity of class to struct comparison with respect to the language...

Thread Thread
 
stewieandro profile image
Stuart Slaugh

Javascript is not OOP. When Mr.Stejskal claims everything is an object with methods & properties, he demonstrates the fact that a lot of very good developers know very little about JS. Yes, almost everything is an object, but the semantic meaning of that word is quite different. JS objects are very loosely organized properties and/or methods. Data hiding is possible, but it's not simply a question of declaring a property private. You have to build that feature yourself with closures. Because it is much more accurate to compare JS to Lisp or Scheme! Most problems in JS are solved by combining discreet functions. You can write performant efficient code without using any OO patterns whatsoever. Prototypes are NOT equivalent to, e.g. Java objects. You do not instantiate an instance of an object with a class. There ARE no classes in JS. Object literals can in fact modify their prototype, and this change becomes available to all objects that share that ptototype. Prototypes basically describe the capability of a particular object. They are much closer to function declarations than traditional objects. The 'new' operator and constructor functions do not behave like they would in Java. As Mjhd stated, that's syntactic sugar aimed at OO developers.

Thread Thread
 
xroal profile image
Roman Stejskal

We're arguing that PHP, which does not even have first-class support for classes (you have to use strings to pass them around, and ::class just expands to a string) is somehow more OO than JavaScript. PHP, where primitives have no attributes or methods, is more OO than a language in which basically everything is an object.

Take a look at Smalltalk, designed by Alan Kay, who coined the term "object-oriented programming". In Smalltalk, everything is an object. Number, string, file, compiler, you name it, it's an object. In fact, a class is an object which creates instances. Right.

You also don't write typical classes like in C++, Java or C#. Instead, there is an Object object which accepts a subclass message in which you describe how instances of that subclass will look like. That description itself is an object of the Metaclass class.

Smalltalk has single inheritance and every class inherits from a superclass.
The Integer class inherits from Number, which in turn inherits from Magnitude, and Magnitude inherits from Object, which is the root object. Much like prototypes in JavaScript, eh?

Also, classes, being just objects, can accept messages! There's no new MyClass construct, you send a message to the class object asking it to instantiate and return a new instance of itself.

Heck, even our well known if condition breaks OO design. In Smalltalk, a comparison like a < b gives you an object of the Boolean class which has ifTrue and ifFalse methods. There's no usual if (condition) { code } else { code } construct.

The class keyword as we know it from C++, Java, C# or PHP is not a mandate of object-oriented language. Using objects that communicate via messages and nothing but that is a mandate for object-oriented language.

PHP fails at this, and so does JavaScript. Neither of them is fully object-oriented, obviously, but I dare to say that JavaScript is much closer to what an object-oriented language looks like than PHP.

Collapse
 
laughingraven profile image
Laughing Raven • Edited

There are too many know-it-alls in this world. The comments people have made on your post support that.
As for the question, I think it depends on how the back end will be used and in what environment.

Collapse
 
razbakov profile image
Aleksey Razbakov

Do you have experience in both?

Collapse
 
laughingraven profile image
Laughing Raven

I have been in this business long enough to know that having a "favorite language" is foolish. There is only the problem and then the solution. Languages are simple a vehicle to solve a problem. The real mark of excellence is understanding the domain of interest in such a way as to plan an effective solution. PHP is good in some situations and Node in others. Whereas there spheres of appropriateness overlap somewhat, by and large they were created for different problem spaces.

Collapse
 
octopoulos profile image
octopoulos

I have professional experience with both PHP (almost 15 years, from 4.3 to 7.1) and Node.js (2 years, however I already knew javascript, so I wasn't starting from scratch). I'm no longer using PHP for any project, as to me, there's no comparison. I always felt PHP was a big mess, with poor backward compatibility
(just showing how poorly designed it is) and very prone to difficult to find bugs, and also, I don't like stateless systems and with PHP you need to keep saving and reloading a state to approach a stateful system, which also slows down the request. With good programming in Node.js, you can achieve much faster speed and much more easily (no need for the above tricks). Something like caching is a piece of cake in Node, or anything involving real time, such as a chat.

I think a lot of PHP users who never tried Node.js are going to say PHP is better, but I think people who have in experience in both most probably prefer Node.js, by far.

Collapse
 
razbakov profile image
Aleksey Razbakov

We have common experience. Same story here. Recently I discovered Symfony Workflow which I love so much, but I can't really imagine how to build something similar with Node. Could you have a look at dev.to/razbakov/symfony-workflow-a...

Collapse
 
tdias25 profile image
Thiago Dias

i bet a thousand dollars that you never used Symfony or Laravel, or even TDD.

Collapse
 
brainbust profile image
BrainBust

There are quite a few tricks to running nodejs at scale in production and the people that have a lot of experience with it wont be very willing to share them as it's their bread and butter. But i guess the same goes for php and large scaled applications.

Here are just a few:

Cluster and cpu bind your nodejs instances, since it's single threaded you're able to cluster all your instances under a master thread (rpc bus). Use a decent process manager like pm2 that does the work for you. pm2.keymetrics.io/

Keep remembering it's event based and use it to it's full potential. Code runs topdown but logic does not. Doing something simple as 'class myEmitter extends EventEmitter' can go a very long way.

Let your app crash, if it crashes make sure it does so in an environment before production, so you can fix it. Never leave a nodejs app in an uncertain state. This goes hand in hand with making sure your app is stateless. If it crashes in production then you made a mistake that should o've never reached production deployment to begin with, costing your company money or even SLAs.

Use active frameworks, npm is one of the biggest packagers out there, both nodejs as browserland, but many package are not actively maintained, search for libraries you know will be supported and bugfixed. Like nestjs.com/

 
razbakov profile image
Aleksey Razbakov

I am doing my project with Node already more than a year now. Cloud functions in Firebase and REST with Express. It got wild and chaotic. I can't get it organized. I can't even test it properly. While at work I am getting deeper with Symfony, which got all those Bundles, Interfaces, DI.

So I am hesitating now on how to proceed. I want to get most of logic out of cloud functions and do them as microservices. What I want to achieve is a good logging and some admin panel to be able to navigate quickly and flexible through the data. So far I understand that the best way to connect microservices is through some kind of queue and state machine. Firebase has a big limitation on filtering (which I need most for admin) and I am afraid I can't control the costs (it can get wild with more data), so I want to move all logic on own server and be able limit what and when to process. So far all triggers are on onWrite functions of Firestore documents. So it can get out of control real quick. I haven't found yet any alternative to Symfony in Node yet, that can allow me to do all the things. Neither I can migrate 100% to PHP, because there are some packages that only available in Node.

After a while working with Firebase it gets annoying, because you have to find workarounds to build your data model. Normalized thinking from MySQL you can forget right away. Neither NoSQL thinking works, because Firebase is not flexible enough with queries.

It's very painful and annoying. I already have an idea how to build it with API Platform in a way, but I want to give it a chance everything based on Node. Unfortunately I can't find good examples of something complex built on Node and it's like walking around and trying to find all the small pieces first and build a new thing. That always felt wrong in PHP world. There is always something working out there, some framework, some concept, some structure. In Node it feels like lots of small libraries which do the same thing and have releases faster than I deploy a new version of the app. And sometimes projects just get archived without any explanation of what happened.

I still have hopes that I have wrong perception and it's just takes time to learn and find a right thing.

Collapse
 
peon501 profile image
Matas Lesinskas • Edited

In short it depends. Use node.js if you work with real-time socket io app, event based system or with multiple threads.
That might be simpler than trying to achieve something like that in php.
On another hand php let's you write really nice run and exit programs faster. Also with php it's really nice to work in oop and with variables, because you don't need to handle undefined, null and other similar problems. Also I like php arrays and JavaScript fuckery kind of sucks.

Overall I use php on large projects where I need stable and secure system.

Node.js is kind of new and still you can't trust it on Enterprise level.

If you read somewhere that php is insecure it's wrong. People who never worked in php and back end wrote it or they are just script kiddes who used old WordPress and got spam and viruses inserted. Tho we can all agree WordPress is trash. Why they still use plain php for templates? Lol.

Collapse
 
agungdarmanto profile image
Agung Darmanto

PHP using Laravel is still worth for me on most of my current projects with all awesome libs and features that easy and quick to implement.

In other hand, I also use NodeJs specially using ExpressJs for a project that I think it shouldn't use PHP at all, e.g all requirements are depended on npm packages.

Conclusion, you can feel it whether is the best or not by yourself. :)

Collapse
 
sfxworks profile image
Samuel Walker

Node if you want to do cloud work.

Collapse
 
razbakov profile image
Aleksey Razbakov

How would you implement state machines in Node? I am looking for a solid alternative to Symfony Workfow Component.

Collapse
 
tracker1 profile image
Michael J. Ryan

Depends on what you are trying to do... I use refund patterns.

Collapse
 
juelcf profile image
Just another dev

Server Side PHP is the way to go.

dev.to/brewer1_jane/why-php-is-the...

Collapse
 
mojskin profile image
MojSkin • Edited

I prefer PHP and Laravel as backend, and also a JS framework as fronted like VUE. Laravel is really nice, easy, handy and secure to develop a mid range project. I have to say, I love it!

Collapse
 
mabalashov profile image
mabalashov

Node is the best for BFF applications
PHP is the best for enterprise application with a lot of business logic

You should choose the platform for your current aims

You should choose NodeJS if:

  • you are going to create a small application for one evening
  • you have no experience in backend and you need a server part for your frontend
  • you have a lot of IO (ex. sockets) in application
  • you have enough experience in both technologies and you understand the pros and cons of each one

In other cases (especially if you want your application to be secure and reliable) you should choose PHP

Long story short, the main differences are:

  • PHP dies after each request => you should care less about memory leaking and secure. But each request is more expensive in PHP if we are talking about performance
  • It is easier to write clear code in PHP because of the mature environment and language-specific features. PHP is a really OOP language. Yes, JS has TypeScript but it is simpler to use C# instead of TS
Collapse
 
patryktech profile image
Patryk • Edited

Python 🐍🐍🐍

Want sink included? Django 😍😍

Want something lightweight? Flask 🤙

PHP should be relegated to legacy software from 2003. 💩💩💩

Don't know enough about node to judge, but JavaScript is nice.

Collapse
 
tracker1 profile image
Michael J. Ryan

Python is cool... There are some interesting libraries for rust as well. I tend to favor node myself. I've never liked PHP, not to mention node/js jobs tend to pay better, especially if you're experienced with react.

Collapse
 
perttisoomann profile image
Pert Soomann

PHP. For all the talk about concurrent connections and all that, can't beat the fact that one broken route in PHP does not affect rest of the code.

Collapse
 
sinapis profile image
sinapis

The question should be the other way around.

Node has:

  1. The larger (if not largest) eco system
  2. Better performance
  3. Better tooling. Code navigation + refactoring is top notch when using Typescript. Git integration, linting, code coverage, testing, package management etc. Are also the same or better.
  4. Same language as the front-end we all use.
  5. Anything you can implement with php, you can implement with typescript.

Now, what does PHP has to offer?

Collapse
 
ganey profile image
Ganey

Depends on the usage. I regularly work with Node, PHP, go and python for managing backend, each has benefits and flaws.

While I prefer nodes package management, I keep getting screwed by package updates that won't download or compile.

PHP composer is just slow compared to node/yarn (yarn comes with its own issues when you're automating deployments)

Typescript is generally a must, I hate reading new code with braces and arrows everywhere to the point where I can't figure it out.

I'm mostly a PHP dev but do debugging and IoT work in node environments.

Python and Go are just for gluing everything together 😁

Collapse
 
tracker1 profile image
Michael J. Ryan

If you aren't targeting Windows for deployments.. using docker where you use the build order, you can get some version layer calling and fewer issues in practice for ci/CD... I try to update all packages and test about once a month to reduce friction though.

Collapse
 
hassanimtiaz26 profile image
hassanimtiaz26

I mostly work with PHP (Laravel) for backend with angular or react as frontend. I also use Node from time to time. Depends on the project to be honest.

Personally, I don't really have any preference that I HAVE to use one over the other :P

Collapse
 
massivebrains profile image
Segun Olaiya

I prefer PHP. As much as I use node (express, adonisJs etc) perhaps it could be because of my experience, I think until I have specific requirements that requires the strengths of node, I would choose Laravel everytime.

I love node no doubt, but I seem to have enjoyed alot or stability in my existing PHP backend systems.

Collapse
 
tracker1 profile image
Michael J. Ryan

You mean do I prefer a better language, in a more consistent platform, with the largest third party developer ecosystem software has ever seen?

Yes. Personally, I cannot stand PHP. Nearly every common complaint about JS applies to PHP and then some.

Collapse
 
redeemefy profile image
redeemefy • Edited
  • This is for learning purpose or for a real project?
  • This is for a team or solo developer?
Collapse
 
razbakov profile image
Aleksey Razbakov

It is more about your personal experience and feeling.

This is for learning purpose or for a real project?

Both. I am a PHP developer and I decided to start a Quasar + Firebase project for learning purposes. It is already being a year me working on this project and now I deep stuck with decision how to proceed. I need now to add job queues and proper logging. Probably it is also better to have own database aside.

This is for a team or solo developer?

For now solo, but it should be scalable.

Collapse
 
redeemefy profile image
redeemefy

If you know how to do this on PHP, I will go Node just for the sake of learning.

Collapse
 
echorris profile image
Eric • Edited

Dockerize your environments and use any of the many queueing systems to manage your processes. E.g. RabbitMQ. I'd stick with php, it has its quirks but I love it over all other languages personally.

Collapse
 
razbakov profile image
Aleksey Razbakov

The best answer so far! What do you think of Prisma or some Headless CMS, would you consider it as an alternative to API Platform?

Collapse
 
anomaly2009 profile image
Ibne Nahian

PHP vs Node is not a valid comparison. PHP is a language whereas Node is a JS runtime. PHP seems little primitive to me. Node is more efficient for Asynchronous / Non Blocking systems. Node is basically a good VM lacking a good language.

Collapse
 
randompages profile image
random pages

no. still php

Collapse
 
ismail9k profile image
Abdelrahman Ismail

Is PHP considered as a programming language, compared to Node.js?

Collapse
 
vlasales profile image
Vlastimil Pospichal

Yes, PHP is considered as a programming language. NodeJS too.

Collapse
 
thekingofwit profile image
Brian Barrett

As far as I understand, Node isn't a programming language, JavaScript is. Node is a runtime environment that lets you execute JavaScript outside of the browser.

Thread Thread
 
andreidascalu profile image
Andrei Dascalu

Exactly. A fair comparison would be node vs roadrunner for php. Even fpm isn't really a proper comparison since it only connects prerouted requests for php scripts with the php interpreter.

The mess is that there are technically 2 php interpreters, php cli and the one tied to fpm, both configurable separately.

Collapse
 
motss profile image
Rong Sen Ng • Edited

Neither or it depends.

Collapse
 
joshlive77 profile image
Su_Do

Node

Collapse
 
roham96 profile image
Roham

😍✋😁

Collapse
 
sunnepazzy123 profile image
sunnepazzy123

I prefer Php at backend because it easy for beginners...
But NodeJs is superb when it come to backend...

Collapse
 
rosseyn profile image
Rosseyn

Never again with the php.

Collapse
 
fyapy profile image
aabdullin

Websockets my love🙂

Collapse
 
franksierra profile image
Frank Sierra

Depending on your final goal I can give you advice.

As is, this is too open and will end in personal preference.

Collapse
 
weylar profile image
Idris

I use php (laravel) mostly for my backend logics. Although Node.js is now taking over