Does Yii2 create a new application instance for every request?

I was reading the source code of index.php in Basic Template when I suddenly noticed the last line “(new yii\web\Application($config))->run();”, It occurs to me if Yii 2 will create a new yii\web\Application instance for each request.

I used to be a Java coder, but now I’m a PHP newbie. So I’m wondering if Yii 2 or PHP will cache such a heavy object for reusing, and if at some moment it will be auto-released, just like a Java object stay in Java Virtual Machine.

I know that an application instance is attached to \Yii class. So a related question is: how long will the \Yii class stay in the PHP environment(or we can call it “PHP Virtual machine”)? So we can get it for next requests?

Hi @wenjiehu,

Simply, YES.
Not only Yii, but each and every PHP program create new objects for every request. And every objects are abandoned after the response is sent. There’s nothing in PHP that we could call “PHP virtual machine”.

Usually we would enable the op code cache, but it doesn’t store the state of objects, it only helps PHP to load code from the source files.

Please check the following sections of the guide.

https://www.yiiframework.com/doc/guide/2.0/en/runtime-overview
https://www.yiiframework.com/doc/guide/2.0/en/runtime-bootstrapping

1 Like

@softark Thanks for reply.

Actually, I’ve already known PHP will create and then release all objects for each request before. I asked this question because later I read this sentence in “Bootstrapping Components” section

As mentioned above, an application component will only be instantiated when it is being accessed the first time. If it is not accessed at all during a request, it will not be instantiated. Sometimes, however, you may want to instantiate an application component for every request, even if it is not explicitly accessed.

Because of the “for every request”, so I thought an application component would be shared for multi requests.

Nowadays there are some ways to save application between requests, namely RoadRunner and unofficial yii2 adapter, but it’s not a typical usecase and there are some caveats and limitations.

BTW, PHP 7.4 preloading is some option here.