9102 年的 PHP
PHP
![](/data/attachment/album/201905/18/183202tdg7r7g5kl3du7ms.jpg)


你还记得篇流行的博客文章《[PHP：设计糟糕的分形](https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/)》吗？我第一次读到它时，我在一个有很多遗留的 PHP 项目的糟糕地方工作。这篇文章让我觉得我是否应该放弃，并去做与编程完全不同的事情。


还好，我之后很快就换了工作，更重要的是，自从 5.x 版本以来，PHP 成功地进步了很多。今天，我在向那些不再使用 PHP 编程，或者陷入遗留项目的人们致意。


剧透：今天有些事情仍然很糟糕，就像几乎每种编程语言都有它的怪癖一样。许多核心功能仍然有不一致的调用方法，仍然有令人困惑的配置设置，仍然有许多开发人员在那里写蹩脚的代码 —— 因为他们必须如此，或是他们不知道更好的写法。


今天我想看看好的一面：让我们关注已经发生变化的事情，以及编写干净而可维护的 PHP 代码的方法。在此之前，我想请你暂时搁置任何偏见。


然后，你可以像以前一样对 PHP 自由吐槽。虽然，你可能会对 PHP 在过去的几年里的一些改进感到惊讶。（LCTT 译注：说实话，我是真的感到吃惊）


### 提前看结论


* PHP 在积极地开发，每年都有新版本
* 自 PHP 5 时代以来的性能已经翻倍，如果不是三倍的话
* 有一个非常活跃的框架、包和平台的生态系统
* PHP 在过去几年中添加了许多新功能，并且这种语言在不断发展
* 像静态分析这样的工具在过去几年中已经成熟，并且一直保持增长 更新：人们让我展示一些实际的代码。我觉得这没问题！这是我的一个业余项目的[源代码](https://github.com/brendt/aggregate.stitcher.io)，用 PHP 和 Laravel 编写的；[这里](https://spatie.be/open-source/packages)列出了我们在办公室维护的几百个自由开源软件包。这两者都是现代 PHP 项目的好例子。


那让我们开始吧。


### 历史总结


出于更好地衡量的目的，让我们快速回顾一下如今的 PHP 发布周期。我们现在的 PHP 为 7.3，预计在 2019 年底为 7.4。PHP 8.0 将是 7.4 之后的下一个版本。


自从 5.x 时代以来，核心团队试图保持每年发布一个版本的周期，并且他们在过去的四年中成功地做到了这一点。


一般来说，每个新版本都会在两年内得到积极支持，并再获得一年以上的“安全修复”。其目标是激励 PHP 开发人员尽可能保持最新：例如，每年进行小规模升级比在 5.4 到 7.0 之间跳转更容易。


可以在 [这里](https://www.php.net/supported-versions.php) 找到 PHP 时间轴的活动概述。


![](/data/attachment/album/201905/18/182816searmxew6rmq692a.jpg)


最后，PHP 5.6 是最新的 5.x 版本，而 8.0 是当前的下一个大版本。如果你想知道 PHP 6 发生了什么，你可以听听 [PHP Roundtable 播客](https://www.phproundtable.com/episode/what-happened-to-php-6)。


了解了这个，让我们揭穿一些关于现代 PHP 的常见误解。


### PHP 的性能


早在 5.x 时代，PHP 的表现就是……嗯，平均水平。但是在 7.0 版本中，PHP 从头开始重写了核心部分，导致其性能提升了两到三倍！


但光是嘴说是不够的。让我们来看看基准测试。幸运的是，人们花了很多时间对 PHP 性能进行了基准测试。 我发现 [Kinsta](https://kinsta.com/blog/php-benchmarks/) 有一个很好的更新的测试列表。


自 7.0 升级以来，性能就一直在提升而没有回退。PHP Web 应用程序的性能可与其它语言中的 Web 框架相提并论，甚至在某些情况下更好。你可以看看这个[广泛的基准测试套件](https://github.com/the-benchmarker/web-frameworks)。


当然 PHP 框架不会胜过 C 和 Rust，但它们比 Rails 或 Django 要好得多，并且与 ExpressJS 相当。


### 框架和生态系统


说到框架：PHP 可不仅仅是 WordPress。让我告诉你 —— 某些专业的 PHP 开发人员：WordPress 绝不代表当代的 PHP 生态系统。


一般来说，有两个主要的 Web 应用程序框架，[Symfony](https://symfony.com/) 和 [Laravel](https://laravel.com/)，以及一些较小的应用程序框架。当然还有 Zend、Yii、Cake、Code Igniter 等等，但是如果你想知道现代 PHP 开发是怎么样的，这两者之一都是很好的选择。


这两个框架都有一个庞大的包和产品的生态系统。从管理面板和 CRM 到独立软件包，从 CI 到分析器，以及几个 Web 套接字服务器、队列管理器、支付集成等众多服务。老实说，要列出的内容太多了。


这些框架虽然适用于实际开发。如果你只是需要个内容管理系统（CMS），WordPress 和 CraftCMS 等平台就够了。


衡量 PHP 生态系统当前状态的一种方法是查看 Packagist，这是 PHP 主要的软件包存储库。它现在呈指数级增长。每天下载量达到了 2500 万次，可以说 PHP 生态系统已不再是以前的小型弱势群体了。


请查看此图表，它列出一段时间内的软件包和版本数量变化。它也可以在 [Packagist 网站](https://packagist.org/statistics)上找到它。


![](/data/attachment/album/201905/18/183234wkk9xxfnop0dxxno.png)


除了应用程序框架和 CMS 之外，我们还看到过去几年里异步框架的兴起。


这些是用 PHP 或其他语言编写的框架和服务器，允许用户运行真正的异步 PHP，这些例子包括 [Swoole](https://www.swoole.co.uk/)（创始人韩天峰），以及 [Amp](https://amphp.org/) 和 [ReactPHP](https://reactphp.org/)。


我们已经进入了异步的世界，像 Web 套接字和具有大量 I/O 的应用程序之类的东西在 PHP 世界中已经变得非常重要。


在内部邮件列表里（PHP 核心开发人员讨论语言开发的地方）已经谈到了[将 libuv 添加到核心](https://externals.io/message/102415#102415)。如果你还不知道 libuv：Node.js 全有赖它提供异步性。


### 语言本身


虽然尚未提供 `async` 和 `await`，但在过去几年中，PHP 语言本身已经有了很多改进。这是 PHP 中新功能的非详尽列表：


* [短闭包](https://stitcher.io/blog/short-closures-in-php)（箭头函数）
* [Null 合并操作符](https://stitcher.io/blog/shorthand-comparisons-in-php#null-coalescing-operator)（`??`）
* [Trait](https://www.php.net/manual/en/language.oop5.traits.php)（一种代码重用方式）
* [属性类型](https://stitcher.io/blog/new-in-php-74#typed-properties-rfc)
* [展开操作符](https://wiki.php.net/rfc/argument_unpacking)（参数解包 `...`）
* [JIT 编译器](https://wiki.php.net/rfc/jit)（即时编译器）
* [FFI](https://wiki.php.net/rfc/ffi)（外部函数接口）
* [匿名类](https://www.php.net/manual/en/language.oop5.anonymous.php)
* [返回类型声明](https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration)
* [现代化的加密支持](https://wiki.php.net/rfc/libsodium)
* [生成器](https://wiki.php.net/rfc/generators)
* [等等](https://www.php.net/ChangeLog-7.php)


当我们讨论语言功能时，我们还要谈谈当今该语言的发展过程。虽然社区可以提出 RFC，但是得有一个活跃的志愿者核心团队才能推着它前进。


接下来，这些 RFC 将在“内部”邮件列表中进行讨论，这个邮件列表也可以[在线阅读](https://externals.io/)。在添加新的语言特性之前，必须进行投票。只有得到了至少 2/3 多数同意的 RFC 才能进入核心。


可能有大约 100 人能够投票，但不需要每个人对每个 RFC 进行投票。核心团队的成员当然可以投票，他们是维护代码库的人。除了他们之外，还有一群人从 PHP 社区中被单独挑选出来。这些人包括 PHP 文档的维护者，对 PHP 项目整体有贡献的人，以及 PHP 社区中的杰出开发人员。


虽然大多数核心开发都是在自愿的基础上完成的，但其中一位核心 PHP 开发人员 Nikita Popov 最近受雇于 [JetBrains](https://blog.jetbrains.com/phpstorm/2019/01/nikita-popov-joins-phpstorm-team/) 全职从事于 PHP 语言的开发。另一个例子是 Linux 基金会最近决定[投资 Zend 框架](https://getlaminas.org/)。像这样的雇佣和收购确保了 PHP 未来发展的稳定性。


### 工具


除了核心本身，我们看到过去几年中围绕它的工具有所增加。首先浮现于我脑海中的是静态分析器，比如由 Vimeo 创建 [Psalm](https://github.com/vimeo/psalm)，以及 [Phan](https://github.com/phan/phan) 和 [PHPStan](https://github.com/phpstan/phpstan)。


这些工具将静态分析你的 PHP 代码并报告任何类型错误和可能的错误等。在某种程度上，它们提供的功能可以与 TypeScript 进行比较，但是现在这种语言不能<ruby> 转译 <rt>  transpiling </rt></ruby>，因此不支持使用自定义语法。


尽管这意味着我们需要依赖 docblocks，但是 PHP 之父 Rasmus Lerdorf 确实提到了[添加静态分析引擎](https://externals.io/message/101477#101592)到核心的想法。虽然会有很多潜力，但这是一项艰巨的任务。


说到转译，以及受到 JavaScript 社区的启发；他们已经努力在用户领域中扩展 PHP 语法。一个名为 [Pre](https://preprocess.io/) 的项目正是如此：允许将新的 PHP 语法转译为普通的 PHP 代码。


虽然这个思路已经在 JavaScript 世界中被证明了，但如果提供了适当的 IDE 和静态分析支持，它就能在 PHP 中工作了。这是一个非常有趣的想法，但必须发展起来才能称之为“主流”。


### 结语


尽管如此，你仍然可以将 PHP 视为一种糟糕的语言。虽然这种语言肯定有它的缺点和背负了 20 年的遗产；但我可以放胆地说，我喜欢用它工作。


根据我的经验，我能够创建可靠、可维护和高质量的软件。我工作的客户对最终结果感到满意，“俺也一样”。


尽管仍然可以用 PHP 做很多乱七八糟的事情，但我认为如果明智和正确地使用的话，它是 Web 开发的绝佳选择。


你不同意吗？让我知道为什么！你可以通过 [Twitter](https://twitter.com/brendt_gd) 或 [电子邮件](mailto:brendt@stitcher.io) 与我联系。




---


via: <https://stitcher.io/blog/php-in-2019>


作者：[Brent](https://stitcher.io/blog/php-in-2019) 选题：[lujun9972](https://github.com/lujun9972) 译者：[wxy](https://github.com/wxy) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
# PHP in 2019

Do you remember the popular "[PHP: a fractal of bad design](https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/)" blog post?
The first time I read it, I was working in a crappy place with lots of legacy PHP projects.
This article got me wondering whether I should just quit and go do something entirely different than programming.

Luckily for me I was able to switch jobs shortly thereafter and, more importantly, PHP managed to evolve quite a bit since the 5.* days. Today I'm addressing the people who are either not programming in PHP anymore, or are stuck in legacy projects.

Spoiler: some things still suck today, just like almost every programming language has its quirks. Many core functions still have their inconsistent method signatures, there are still confusing configuration settings, there are still many developers out there writing crappy code — because they have to, or because they don't know better.

Today I want to look at the bright side: let's focus on the things that have changed and ways to write clean and maintainable PHP code. I want to ask you to set aside any prejudice for just a few minutes.

Afterwards you're free to think exactly the same about PHP as you did before. Though chances are you will be surprised by some of the improvements made to PHP in the last few years.

[#](#tl;dr) TL;DR

- PHP is actively developed with a new release each year
- PHP 7.4 is one of the
[most feature-packed](/blog/new-in-php-74)releases ever - Performance since the PHP 5 era has doubled, if not tripled
- There's a extremely active eco system of frameworks, packages and platforms
- PHP has had lots of new features added to it over the past few years, and the language keeps evolving
- Tooling like static analysers has matured over the past years, and only keeps growing

Update: people asked me to show some actual code.
I'm happy to say that's possible! Here's the [source code](https://github.com/brendt/aggregate.stitcher.io)
of one of my hobby projects, written in PHP and Laravel;
and [here](https://spatie.be/open-source/packages) is a list of a few hundred OSS packages we maintain at our office.
Both are good examples of what modern PHP projects look like.

Let's start.

[#](#history-summarized) History summarized

For good measure, let's quickly review PHP's release cycle today. We're at PHP 7.4 now, and PHP 8.0 will be the next version after that.

Ever since the late 5.* era, the core team tries to keep a yearly release cycle, and have succeeded in doing so for the past four years.

In general, every new release is actively supported for two years, and gets one more year of "security fixes only". The goal is to motivate PHP developers to stay up-to-date as much as possible: small upgrades every year are way more easy than making the jump between 5.4 to 7.0, for example.

An active overview of PHP's timeline can be found [here](https://www.php.net/supported-versions.php).

Lastly, PHP 5.6 was the latest 5.* release, with 7.0 being the next one.
If you want to know what happened to PHP 6, you can listen to the [PHP Roundtable podcast](https://www.phproundtable.com/episode/what-happened-to-php-6).

With that out of the way, let's debunk some common misconceptions about modern PHP.

[#](#php's-performance) PHP's performance

Back in the 5.* days, PHP's performance was… average at best. With 7.0 though, large parts of PHP's core were rewritten from the ground up, resulting in two or three times performance increases.

Words don't suffice though. Let's look at benchmarks.
Luckily other people have spent lots of time in benchmarking PHP performance.
I find that [Kinsta](https://kinsta.com/blog/php-benchmarks/) has a good updated list.

Ever since the 7.0 upgrade, performance only increased.
So much that PHP web applications have comparable — in some cases better — performance than web frameworks in other languages.
Take a look at this [extensive benchmark suite](https://github.com/the-benchmarker/web-frameworks).

Sure PHP frameworks won't outperform C and Rust, but they are equally performant as Django, Rails or Express.

[#](#frameworks-and-ecosystem) Frameworks and ecosystem

Speaking of frameworks: PHP isn't just WordPress anymore. Let me tell you something as a professional PHP developer: WordPress isn't in any way representative of the contemporary ecosystem.

In general there are two major web application frameworks, and a few smaller ones: [Symfony](https://symfony.com/) and [Laravel](https://laravel.com/).
Sure there's also Zend, now called Laminas; Yii, Cake, Code Igniter etc.
— but if you want to know what modern PHP development looks like, you're good with one of the first two.

Both frameworks have a large ecosystem of packages and products. Ranging from admin panels and CRMs to standalone packages, CI to profilers, numerous services like web sockets servers, queuing managers, payment integrations; honestly there's too much to list.

These frameworks are meant for actual development though. If you're in need of pure content management, platforms like WordPress and CraftCMS are only improving more and more.

One way to measure the current state of PHP's ecosystem is to look at Packagist, the main package repository for PHP. It has seen exponential growth. With ±25 million downloads a day, it's fair to say that the PHP ecosystem isn't the small underdog it used to be.

Take a look at this graph, listing the amount of packages and versions over time.
It can also be found on [the Packagist website](https://packagist.org/statistics).

Besides application frameworks and CMSs, we've also seen the rise of asynchronous frameworks the past years.
These are frameworks and servers, written in PHP or other languages,
that allow users to run truly asynchronous PHP.
A few examples include [Swoole](https://www.swoole.co.uk/), [Amp](https://amphp.org/) and [ReactPHP](https://reactphp.org/).

Since we've ventured into the async world, stuff like web sockets and applications with lots of IO have become actually relevant in the PHP world.

There has also been talk on the internals mailing list — the place where core developers discuss the development of the language —
to [add libuv to the core](https://externals.io/message/102415#102415).
For those unaware of libuv: it's the same library Node.js uses to allow all its asynchronicity.

[#](#the-language-itself) The language itself

While `async`

and `await`

are not available yet, lots of improvements to the language itself have been made over the past years.
Here's a non-exhaustive list of new features in PHP:

-
[Short closures](/blog/short-closures-in-php) -
[Union types](https://wiki.php.net/rfc/union_types_v2)(PHP 8.0) -
[Null coalescing operator](/blog/shorthand-comparisons-in-php#null-coalescing-operator) -
[Traits](https://www.php.net/manual/en/language.oop5.traits.php) -
[Typed properties](/blog/new-in-php-74#typed-properties-rfc) -
[Spread operator](https://wiki.php.net/rfc/argument_unpacking) -
[JIT compiler](https://wiki.php.net/rfc/jit)(PHP 8.0) -
[FFI](https://wiki.php.net/rfc/ffi) -
[Anonymous classes](https://www.php.net/manual/en/language.oop5.anonymous.php) -
[Return type declarations](https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration) -
[Contemporary cryptography](https://wiki.php.net/rfc/libsodium) -
[Generators](https://wiki.php.net/rfc/generators) -
[Lots more](/blog/new-in-php-74)

While we're on the topic of language features, let's also talk about the process of how the language is developed today. There's an active core team of volunteers who move the language forward, though the community is allowed to propose RFCs.

Next, these RFCs are discussed on the "internals" mailing list, which can also be [read online](https://externals.io/).
Before a new language feature is added, there must be a vote.
Only RFC with at least a 2/3 majority are allowed in the core.

Recently there has been an effort to move RFC discussions to GitHub, where the code actually lives. It seems like the small group of developers who's actively invested in PHP, are on board. You can read about the process [here](https://externals.io/message/107747).
It's still a work in progress because some people don't like GitHub. It's clear though that the most active contributors are on board with the decision, so it's fair to say the RFC discussion process will be moved to GitHub entirely within the next year or so.

Once an RFC is discussed, it goes into the voting phase. There are probably around 100 people allowed to vote, though you're not required to vote on each RFC. Members of the core team are of course allowed to vote, they have to maintain the code base. Besides them, there's a group of people who have been individually picked from the PHP community. These people include maintainers of the PHP docs, contributors to the PHP project as a whole, and prominent developers in the PHP community.

While most of core development is done on a voluntary basis, one of the core PHP developers,
Nikita Popov, has recently been [employed by JetBrains](https://blog.jetbrains.com/phpstorm/2019/01/nikita-popov-joins-phpstorm-team/)
to work on the language full time.
Another example is the Linux foundation who recently decided to [invest into Zend framework](https://getlaminas.org/), now called Laminas.
Employments and acquisitions like these ensure stability for the future development of PHP.

[#](#tooling) Tooling

Besides lots of features and improvements added to PHP's core, we've seen an increase in tools around it the past few years.
What comes to mind are static analysers like [Psalm](https://github.com/vimeo/psalm), created by Vimeo;
[Phan](https://github.com/phan/phan) and [PHPStan](https://github.com/phpstan/phpstan).

These tools will statically analyse your PHP code and report any type errors, possible bugs etc. In some way, the functionality they provide can be compared to TypeScript, though for now the language isn't transpiled, so no custom syntax is allowed.

Even though that means we need to rely on docblocks, Rasmus Lerdorf, the original creator of PHP,
did mention the idea of [adding a static analysis engine](https://externals.io/message/101477#101592) to the core.
While there would be lots of potential, it is a huge undertaking.

Speaking of transpiling, and inspired by the JavaScript community;
there have been efforts to extend PHPs syntax in user land.
A project called [Pre](https://web.archive.org/web/20190828000023/https://preprocess.io/#/) does exactly that:
allow new PHP syntax which is transpiled to normal PHP code.
While the idea has proven itself in the JavaScript world,
it could only work in PHP if proper IDE- and static analysis support was provided.
It's a very interesting idea, but has to grow before being able to call it "mainstream".

[#](#in-closing) In closing

All of that being said, feel free to still think of PHP as a crappy language. While the language definitely has its drawbacks and 20 years of legacy to carry with it; I can say in confidence that I enjoy working with it.

In my experience, I'm able to create reliable, maintainable and quality software. The clients I work for are happy with the end result, as am I. While it's still possible to do lots of messed up things with PHP, I'd say it's a great choice for web development if used wise and correct.

Don't you agree? Let me know why!
You can reach me via [Twitter](https://twitter.com/brendt_gd) or [e-mail](mailto:brendt@stitcher.io).