백엔드 개발 PHP 튜토리얼 PHP + Apache Stack vs Node.js_PHP教程

PHP + Apache Stack vs Node.js_PHP教程

Jul 13, 2016 pm 05:54 PM
apache node.js php stack this

 This is an apples to oranges comparison. PHP is an older language, running behind the Apache web server in a request/response fashion. Node.js is a non-blocking event-loop framework running JavaScript within the V8 engine, with an optional web server built in. Then again, is it really an apples to oranges comparison? Both technologies are commonly used to serve webpages to browsers.
If you’ve been following my blog through the years, you’d know that I’m a big PHP fan. I earned my PHP5 ZCE (Zend Certified Engineer) certificate a few years back. I’ve built a couple hundred content-based websites using various Content Management Systems, as well as a dozen or so apps using different PHP Frameworks. I had a blast at the 2011 ZendCon, and I’ve even taught a PHP meetup for about nine months.
 
If you’ve been reading my blog as of late, you’ll also notice that I won’t shut up about this new thing called Node.js (Browser-Less JavaScript). Surely, I haven’t thrown away my years of PHP experience for this new kid on the block, right?
 
Honestly, I’ve been using both languages recently. At work our websites are built using PHP (although I’m finding more reasons for Node.js each day). For my side projects, I’m writing multiplayer web games and hardware interfacing software using Node.js.
 
Both environments have their pros and their cons, and neither language is the perfect solution for every project. In this post I’m going to compare and contrast the two environments, covering their strengths and weaknesses, and outline which is better for various situations.
 
Why am I only covering PHP+Apache and Node.js? Honestly, they’re the language I know best and have production code running for each. Ruby and Python are some great languages in this same space with comparable strengths and weaknesses, but I never had the opportunity to learn them. JavaScript (Node.js) and PHP both have syntax influenced by C.
 
Strengths of PHP
PHP is by far the most widely used server-side web programming language. It is old, and there is never short supply of cheap, shared hosting providers. Some of the largest and commonly used platforms/apps use PHP. WordPress, the most popular of self-hosted blogging platforms is PHP. MediaWiki, Joomla, are some more common self hosted apps which use PHP.
 
Some of the biggest websites use PHP, such as Facebook, Wikipedia. PHP uses traditional (read, familiar) Object Oriented methodologies. There are loads of PHP web frameworks and language documentation.
 
PHP is great for serving up content websites. PHP sits behind a web server, which can check to see if the file being requested exists in the filesystem. If so, the file can be served to the client without needing to run any PHP code. This isn’t necessarily a pro of the language itself, but it is a beneficial side-effect for most situations.
 
PHP also has corporate backing by the Zend company (Their tagline is “The PHP Company”). This backing is required by big corporations, which all share the same philosophy, “If something doesn’t cost money we don’t want it”.
 
Weaknesses of PHP
PHP is not meant to be run for extended amounts of time. Many will argue with me here, but the language by default is set to terminate itself once it has been running for 30 seconds, or if it reaches a certain amount of memory usage. This can be disabled, and apps can be built to run for a long time successfully, but this is not where PHP shines.
 
The language isn’t able to run code in parallel. You can, using tools like Gearman, pass off some work to be handled by other processes, and kinda keep an eye on the progress, but the process is rather klunky, and is not what PHP is intended for. Gearman itself offers some other great features and can be used by many different environments, including Node.js.
 
Back in the day, when URLs and filesystems had a 1:1 mapping, it made perfect sense to have a web server separate from the language it is running. But, nowadays, any PHP app with attractive URLs running behind the Apache web server is going to need a .htaccess file, which tells the server a regular expression to check before serving up a file. Sound complex and awkward with unnecessary overhead? That’s because it is.
 
Overall, the stack required to support PHP is overly complex when compared to something simpler like Node. One needs Apache, which has some global settings as well as site specific settings. One also needs PHP, which has global php.ini settings, some of which can be overridden at run time (but not all). There is also a bunch of old stuff left around which should be removed, e.g., y2k support (finally removed in 5.4).
 
The official website is quite ugly and outdated. The docs are okay, the user contributed notes are very useful, however the method to update docs involves SVN and hacking away at XML files, and is not exactly encouraging for most people to write docs.
 
Package management is virtually non-existant. Sure, there is PEAR, but that tool is ridiculously painful to use. Some other package managers have appeared, e.g. Pyrus (PEAR2) and Packagist, but usage is so scattered that there is no de facto standard. There probably never will be to be honest. There is also PHPClasses.org, but this site is painful to use and requires a signed-in user to browse.
 
Since a PHP process starts, does some boilerplate work, performs the taks the user actually wants, and then dies, data is not persistent in memory. You can keep this data persistent using third party tools like Memcache or traditional database, but then there is the overhead of communicating with those external processes.
 
Strengths of Node.js
Node.js’s biggest strength, IMO, is that it is event driven. Node apps run great over long periods of time. The event emitter code, while pretty simple at its core, provides a powerful and consistent interface for triggering code execution when needed.
 
Node has a web server built in. Some people call this a bad thing, I call those people crazy. Having the server built in means that you don’t have the awkward .htaccess config thing going on. Every request is understood to go through the same process, without having to hunt through the filesystem and figure out which script to run.
 
The number one bottleneck with web apps is not the time it takes to calculate CPU hungry operations, but rather network I/O. If you need to respond to a client request after making a database call and sending an email, you can perform the two actions and respond
when both are complete.
 
Of course, with Node.js being written in JavaScript, if you already know JS for frontend development, you are doing pretty good in the Node.js realm. You already know the syntax, and the gotcha’s of the language, all that is left is an API for interacting with the system.
 
The package management system, npm, is great (although the website leaves much to be desired). Instead of having to follow strict guidelines and formatting requirements (e.g. PHP’s PEAR), anyone can put anything into npm (even me!). It is similar to the Android market. Sure, you can get some crappy things out of it, but if one uses common sense they won’t be downloading a virus.
 
Being so new, it doesn’t have a lot of baggage leftover from days of old. Having a server built in, the stack is a lot simpler, there are less points of failure, and there is more control over what you can do with HTTP responses (ever try overwriting the name of the web server using PHP?).
 
Data can be persisted in memory very easily, so if you are sharing data between different clients (e.g. with a multiplayer game), this sharing of data is built in.
 
Weaknesses of Node.js
Node.js is a very new, API unstable, untested platform. If you are going to be building a large corporate scale app with a long lifetime, Node.js is not a good solution. The Node API’s are changing almost daily, and large/longterm apps will need to be rewritten often.
 
If you are serving up a lot of static files, such as images, you don’t want to use Node.js, otherwise you get back to the situation where you are checking the filesystem if things exists. This can be fixed by moving all static content to a subdomain or Content Delivery Network.
 
JavaScript is a far from perfect language, having been created over a 10 day period. If you are a traditional Class based developer, getting used to a Functional programming language can be painful. Getting used to asynchronous programming can also be difficult.
 
The persistent memory thing can be a little tricky. If you don’t know what you’re doing, you might accidentally share data between clients (which could be a disaster). Also, you are in bigger danger of memory leaks. If you keep appending data to an array in PHP, the script only really has a lifetime of 0.1 seconds, but your Node.js script needs to run forever, and you can easily blow it up over a period of time.
 
Node is single threaded, even though it kind of appears to be multithreaded with the asynchronous execution it does. This doesn’t really matter too much, when is the last time your app’s biggest bottleneck was CPU instead of waiting on network I/O? So, while it would be cool to be multi-threaded, it doesn’t usually harm an app.
 
Which should I learn?
This is a great question. If you don’t have any experience developing server side software, you should probably start off with PHP. It is a great, easy language for performing the request -> response pattern which makes the stateless internet great. You will surely find more forum posts from people having the same problem as you (even though the posts might be 10 years old).
 
If you are looking to build other kinds of software, Node.js may be a safer bet. For example, I’m writing some software which requires code to be triggered by changes made to hardware, such as a wireless network coming into range. Writing this kind of software using PHP would be hacky and painful, but with Node.js it is a breeze.
 
As far as being future proof is concerned, I am not convinced that either language will stand the tests of time. The future of web apps are probably Single Page Applications, where smaller amounts of data are sent over the wire and the frontend is in charge of generating HTML, through the use of websockets. PHP can’t nicely do websockets like Node.js can. However, it is too soon to tell if Node.js will win the asynchronous, event driven language war. Due to the major flaws of JavaScript, a better language could easily kick its ass.
 
Example Situations
Here’s some quick examples of different programming situations and which language you should probably go with.
 
Are you building some sort of daemon? Use Node.
Are you making a content website? Use PHP.
Do you want to share data between visitors? Use Node.
Are you a beginner looking to make a quick website? Use PHP.
Are you going to run a bunch of code in parallel? Use Node.
Are you writing software for clients to run on shared hosts? Use PHP.
Do you want push events from the server to the client using websockets? Use Node.
Does your team already know PHP? Use PHP.
Does your team already know frontend JavaScript? Node would be easier to learn.
Are you building a command line script? Both work.
Simple Equation
Here’s a funny way of looking at things… To emulate the functionality of Node.js using PHP + Apache, you would need a couple other services running. To have Node act the same as PHP, you would simply run a bunch of synchronous code.
 
Node.js ≈PHP + Apache + Memcached + Gearman - complexity
Related Posts
Why Node.js is awesome: A short history of web applications

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477984.htmlTechArticleThis is an apples to oranges comparison. PHP is an older language, running behind the Apache web server in a request/response fashion. Node.js is a non-blocking event-loop framework...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

이전에 몰랐던 후회되는 PHP 함수 7가지 이전에 몰랐던 후회되는 PHP 함수 7가지 Nov 13, 2024 am 09:42 AM

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

2024년 개발자를 위한 상위 10대 PHP CMS 플랫폼 2024년 개발자를 위한 상위 10대 PHP CMS 플랫폼 Dec 05, 2024 am 10:29 AM

CMS는 콘텐츠 관리 시스템을 의미합니다. 사용자가 고급 기술 지식 없이도 디지털 콘텐츠를 생성, 관리 및 수정할 수 있는 소프트웨어 애플리케이션 또는 플랫폼입니다. CMS를 사용하면 사용자가 콘텐츠를 쉽게 생성하고 구성할 수 있습니다.

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

PHP와 소셜 미디어: 귀하의 웹사이트를 전 세계와 통합하세요 PHP와 소셜 미디어: 귀하의 웹사이트를 전 세계와 통합하세요 Oct 11, 2024 am 11:54 AM

PHP는 웹사이트에서 소셜 미디어 기능을 쉽게 통합할 수 있는 도구를 제공합니다. 1. 사용자가 콘텐츠를 공유할 수 있도록 소셜 미디어 공유 버튼을 동적으로 생성합니다. 2. 원활한 소셜 미디어 로그인을 달성하기 위해 OAuth 라이브러리와 통합합니다. 3. 소셜 미디어를 캡처하기 위해 HTTP 라이브러리를 사용합니다. 미디어 데이터, 사용자 프로필, 게시물 및 기타 정보를 얻습니다.

See all articles