前文《PHP后台进程/异步处理的用法及在Drupal中的应用》讲解了如何在PHP和Drupal中使用异步处理的方法,该方法应用的是操作系统的后台进程,本文讲解另一种异步处理的方法。
ignore_user_abort
这是一个PHP运行时的参数,如果设置为1,那么PHP程序会一直运行直到程序结束,而不论当前的HTTP请求是否已经关闭。所以,我们可以这样假设,给用户快速返回想要的运行结果,把和用户界面无关的操作放到后面继续运行,那么就可以提高页面的响应速度,提高用户的页面体验,从而侧面提高网站的性能。
不过这个操作没有像之前方法中的后台进程那样简单,这个需要对HTTP协议已经PHP进程的运行有所了解。
幸运的是,Drupal的boost模块已经实现了一个版本,我们可以直接参考或者拿来用。代码如下:
/** * Output text & set php in async mode. * * @param $output * string - Text to output to open connection. * @param $wait * bool - Wait 1 second? * @param $content_type * string - Content type header. */ function boost_async_opp($output, $wait = TRUE, $content_type = "text/html; charset=utf-8", $length = 0) { // Calculate Content Lenght if ($length == 0) { $output .= "\n"; $length = (mb_strlen($output, '8bit')-1); } // Prime php for background operations $loop = 0; while (ob_get_level() && $loop < 25) { ob_end_clean(); $loop++; } header("Connection: close"); ignore_user_abort(); // Output headers & data ob_start(); header("Content-type: " . $content_type); header("Expires: Sun, 19 Nov 1978 05:00:00 GMT"); header("Cache-Control: no-cache"); header("Cache-Control: must-revalidate"); header("Content-Length: " . $length); header("Connection: close"); print($output); ob_end_flush(); flush(); // wait for 1 second if ($wait) { sleep(1); } // text returned and connection closed. // Do background processing. Time taken after should not effect page load times. } |
这个函数没有任何依赖,所以在其他的PHP框架中,我们可以直接拿来用。
如何使用呢?请看下面的示例:
//基本示例: $output = get_output(); //get output for page boost_async_opp($output, FALSE, 'text/html; charset=utf-8'); //send $output //do some operations //Ajax/JSON 示例: $output = Drupal_json($data); boost_async_opp($output, FALSE, 'text/javascript; charset=utf-8'); //send json //继续其他操作 |
如果我们使用了Boost模块,那么这个函数可以直接使用,如果没有,可以直接把这个函数copy到自己的代码中使用。
参考前文:PHP后台进程/异步处理的用法及在Drupal中的应用
声明:
本站所有文章欢迎转载,所有文章未说明,均属于原创,转载均请注明出处。
本文有效链接:
http://www.drupal001.com/2012/05/php-async-operation/
版权所有:
Drupal与高性能网站架构
http://www.drupal001.com
发表评论