考虑以下场景:
-
http://www.restserver.com/example.php
返回一些我想在我的web应用程序工作的内容。 -
我不想用ajax加载它(SEO问题等)
-
我的页面需要100ms生成,REST资源也需要100ms加载
-
我们假设我的网站的100ms生成时间发生在我开始使用REST资源之前。
示例代码:
我的网站Index.php
<?
do_some_heavy_mysql_stuff(); // takes 100 ms
get_rest_resource(); // takes 100 ms
render_html_with_data_from_mysql_and_rest(); // takes neglectable amount of time
?>
网站将需要~200ms生成。
我想把它变成:
<?
Restclient::initiate_rest_loading(); // takes 0ms
do_some_heavy_mysql_stuff(); // takes 100 ms
Restclient::get_rest_resource(); // takes 0 ms because 100 ms have already passed since initiation
render_html_with_data_from_mysql_and_rest(); // takes neglectable amount of time
?>
网站将需要~100ms生成。
为了实现这一点,我考虑使用这样的东西:
(我很确定这段代码不会工作,因为这个问题是关于如何实现这一点,以及它是否可能。我只是认为一些简单的代码可以最好地演示它)
class Restclient {
public static $buffer;
public static function initiate_rest_loading() {
// open resource
$handle = fopen ("http://www.restserver.com/example.php", "r");
// set to non blocking so fgets will return immediately
stream_set_blocking($handle,0);
// initate loading, but return immediately to continue website generation
fgets($handle, 40960);
}
public static function get_rest_resource() {
// set stream to blocking again because now we really want the data
stream_set_blocking($handle,1);
// get the data and save it so templates can work with it
self::$buffer = fgets($handle, 40960); templates
}
}
最后一个问题:
这是可能的吗?
我需要关注什么(内部缓冲区溢出,流长度等)
有更好的方法吗?
这是否很好地工作与http资源?
欢迎输入!
作为"任何输入都是感激的",以下是我的:
- 你想要的被称为异步(你想要做一些事情,而其他事情正在"后台"完成)。
为了解决你的问题,我想:
-
将
do_some_heavy_mysql_stuff
和get_rest_resource
分别放在两个不同的PHP脚本中 -
使用cURL"multi"功能来执行同步请求。请检查:
- curl_multi_init和相关PHP函数
在PHP中使用cURL同时发送HTTP请求
这样,您可以同时执行两个脚本。使用cURL的多种功能,您可以同时调用http://example.com/do_some_heavy_mysql_stuff.php
和http://example.com/get_rest_resource.php
,然后在它们可用时立即使用结果。
这些是我的第一个想法,我要和你分享。也许有不同的更有趣的方法……好运!