PHP 请求生命周期

2021-12-29 00:00:00 php zend-framework vm-implementation

好的,所以我对 PHP VM 的了解还比较幼稚,最近我一直在想一些事情.特别是,Web 应用程序在 PHP 中的请求生命周期是什么样的.我找到了一篇这里的文章,它给出了很好的解释,但我觉得必须有更多的故事.

根据文章的解释,每次向服务器发出请求时都会解析并执行脚本!这对我来说似乎很疯狂!

我正在尝试通过编写一个利用许多 PHP 5.3/5.4 功能的微型框架来学习 PHP.因此,我开始思考 static 的含义以及静态类变量实际存在的时间.我希望我的应用程序可以有一个 setup 阶段,它能够将其结果缓存到具有 static 属性的类中.但是,如果整个脚本在每个请求上都被解析和执行,我就看不出如何避免为每个服务的请求运行应用程序初始化步骤!

我真的希望我在这里遗漏了一些重要的东西......任何见解都非常感谢!

解决方案

根据文章的解释,每次向服务器发出请求时都会解析并执行脚本!这对我来说似乎很疯狂!

不,那篇文章是准确的.有各种方法缓存解析/编译的结果,但脚本是每次都完整地执行.跨请求不会保留类或静态变量的实例.从本质上讲,每个请求都会获得一个全新的、前所未有的应用程序副本.

<块引用>

我不知道如何避免为每个服务的请求运行应用程序初始化步骤!

你不能,也不应该.对于每个请求,您都需要将您的应用程序初始化为某种空白状态.您可以将一堆数据序列化到 $_SESSION 中, 在请求之间持久化,但您不应该这样做,除非您发现确实需要这样做.><块引用>

我真的希望我在这里遗漏了一些重要的东西......

你似乎什么都不担心.默认情况下,世界上每个 PHP 站点都以这种方式工作,而且绝大多数站点无需担心性能问题.

Okay, so I'm relatively naive in my knowledge of the PHP VM and I've been wondering about something lately. In particular, what the request lifecycle looks like in PHP for a web application. I found an article here that gives a good explanation, but I feel that there has to be more to the story.

From what the article explains, the script is parsed and executed each time a request is made to the server! This just seems crazy to me!

I'm trying to learn PHP by writing a little micro-framework that takes advantage of many PHP 5.3/5.4 features. As such, I got to thinking about what static means and how long a static class-variable actually lives. I was hoping that my application could have a setup phase which was able to cache its results into a class with static properties. However, if the entire script is parsed and executed on each request, I fail to see how I can avoid running the application initialization steps for every request servered!

I just really hope that I am missing something important here... Any insight is greatly apreciated!

解决方案

From what the article explains, the script is parsed and executed each time a request is made to the server! This just seems crazy to me!

No, that article is accurate. There are various ways of caching the results of the parsing/compilation, but the script is executed in its entirety each time. No instances of classes or static variables are retained across requests. In essence, each request gets a fresh, never-before execute copy of your application.

I fail to see how I can avoid running the application initialization steps for every request servered!

You can't, nor should you. You need to initialize your app to some blank state for each and every request. You could serialize a bunch of data into $_SESSION which is persisted across requests, but you shouldn't, until you find there is an actual need to do so.

I just really hope that I am missing something important here...

You seem to be worried over nothing. Every PHP site in the world works this way by default, and the vast, vast majority never need to worry about performance problems.

相关文章