File cache (template cache)

From page fragment caching to Facebook’s BigPipe technology

  • Divide the page into small pieces
  • Preprint the contents of the buffer to the browser with ob_flush() and flush()
  • The browser receives a request and renders it to the page, showing it in small chunks.

    • Note: The JavaScript part, which does not need to be executed immediately, can be put in an eval at the end

Program Data -> PHP Buffer -> TCP Buffer -> Client Browers

methods role explain
ob_start() Open the output buffer
ob_flush() Sends the contents of the PHP buffer into the TCP buffer The contents of the buffer are discarded after ob_flush() is called.
flush() Sends the current contents of the TCP Buffer to the user’s browser. The flush() function does not affect the cache mode of the server or client browser. Therefore, both the ob_flush() and flush() functions must be used to flush the output buffer.
ob_get_contents() Returns the contents of the internal buffer Returns false if it gets the contents of the output buffer, but does not clear it
ob_end_clean() Delete the contents of the internal buffer, and close the internal buffer.
ob_end_flush() Sends the contents of the internal buffer to the browser, and closes the output buffer
ob_get_length() Returns the length of the internal buffer

How to use this technology?

  • Nginx needs to be set

sudo vim /etc/nginx/nginx.conf

proxy_buffering off; fastcgi_keep_conn on; gzip off; // Compression is enabled by default
  • So PHP needs to set that

Sudo vim/etc/PHP / 7.0 / FPM/PHP ini

; output_buffering = 4096 output_buffering = off
  • Restart Nginx and PHP
Sudo Service php7.0-FPM Restart Sudo Service php7.0-FPM Restart
  • Used in the template
<? PHP // Start the buffer ob_start(); ? > <? PHP // slow sleep(1); // Sends whatever PHP has executed to nginx or apache ob_flush(); // Nginx or Apache sends the content to the client flush(); ? > <? PHP // Send the final content to the client ob_flush() before shutting down; flush(); // clean the buffer ob_end_clean(); ? >

Realized effects and advantages

When there are many pieces of content on the page, it is possible to brush many pieces of content to the client in batches so that the client does not have to wait for all the content to load before it can see the content. And this technique only has one request. If you use Ajax, you might expect that each piece of content will be requested once using Ajax, so there will be multiple requests.

The original address