搜索
首页后端开发php教程关于PHP你可能不知道的-PHP的事件驱动化设计

最近在做一个需要用到异步PHP的项目, 翻阅PHP源码的时候,发现了三个没有用过的模块,sysvsem,sysvshm,sysvmsg,一番研究以后,受益非浅。

在PHP中有这么一族函数,他们是对UNIX的V IPC函数族的包装。

它们很少被人们用到,但是它们却很强大。巧妙的运用它们,可以让你事倍功半。

它们包括:

信号量(Semaphores)

共享内存(Shared Memory)

进程间通信(Inter-Process Messaging, IPC)

基于这些,我们完全有可能将PHP包装成一基于消息驱动的系统。

但是,首先,我们需要介绍几个重要的基础:

1. ftok

int ftok ( string pathname, string proj )
//ftok将一个路径名pathname和一个项目名(必须为一个字符), 转化成一个整形的用来使用系统V IPC的key

2. ticks

Ticks是从PHP 4.0.3开始才加入到PHP中的,它是一个在declare代码段中解释器每执行N条低级语句就会发生的事件。N的值是在declare中的directive部分用ticks=N来指定的。

function getStatus($arg){
 print_r connection_status();
 
 debug_print_backtrace();
 
}
reigster_tick_function("getStatus", true);
 
declare(ticks=1){
 
 for($i =1; $i<999; $i++){
 
 echo "hello";
 
 }
 
}

unregister_tick_function("getStatus");

这个就基本相当于:

function getStatus($arg){
 print_r connection_status();
 
 debug_print_backtrace();
 
}
 
reigster_tick_function("getStatus", true);
 
declare(ticks=1){
 
 for($i =1; $i<999; $i++){
 
 echo "hello"; getStatus(true);
 
 }
 
}
unregister_tick_function("getStatus");

消息,我现在用一个例子来说明,如何结合Ticks来实现PHP的消息通信。

$mesg_key = ftok(__FILE__, &#39;m&#39;);
$mesg_id = msg_get_queue($mesg_key, 0666);
 
function fetchMessage($mesg_id){
 
 if(!is_resource($mesg_id)){
 
 print_r("Mesg Queue is not Ready");
 
 }
 
 if(msg_receive($mesg_id, 0, $mesg_type, 1024, $mesg, false, MSG_IPC_NOWAIT)){
 
 print_r("Process got a new incoming MSG: $mesg ");
 
 }
 
}
 
register_tick_function("fetchMessage", $mesg_id);
 
declare(ticks=2){
 
 $i = 0;
 
 while(++$i < 100){
 
 if($i%5 == 0){
 
 msg_send($mesg_id, 1, "Hi: Now Index is :". $i);
 }
 }
}
 
//msg_remove_queue($mesg_id);

在这个例子中,首先将我们的PHP执行Process加入到一个由ftok生成的Key所获得的消息队列中。

然后,通过Ticks,没隔俩个语句,就去查询一次消息队列。

然后模拟了消息发送。

在浏览器访问这个脚本,结果如下:

Process got a new incoming MSG: s:19:"Hi: Now Index is :5";
Process got a new incoming MSG: s:20:"Hi: Now Index is :10";
Process got a new incoming MSG: s:20:"Hi: Now Index is :15";
Process got a new incoming MSG: s:20:"Hi: Now Index is :20";
Process got a new incoming MSG: s:20:"Hi: Now Index is :25";
Process got a new incoming MSG: s:20:"Hi: Now Index is :30";
Process got a new incoming MSG: s:20:"Hi: Now Index is :35";
Process got a new incoming MSG: s:20:"Hi: Now Index is :40";
Process got a new incoming MSG: s:20:"Hi: Now Index is :45";
Process got a new incoming MSG: s:20:"Hi: Now Index is :50";
Process got a new incoming MSG: s:20:"Hi: Now Index is :55";
Process got a new incoming MSG: s:20:"Hi: Now Index is :60";
Process got a new incoming MSG: s:20:"Hi: Now Index is :65";
Process got a new incoming MSG: s:20:"Hi: Now Index is :70";
Process got a new incoming MSG: s:20:"Hi: Now Index is :75";
Process got a new incoming MSG: s:20:"Hi: Now Index is :80";
Process got a new incoming MSG: s:20:"Hi: Now Index is :85";
Process got a new incoming MSG: s:20:"Hi: Now Index is :90";
Process got a new incoming MSG: s:20:"Hi: Now Index is :95";

看到这里是不是,大家已经对怎么模拟PHP为事件驱动已经有了一个概念了? 别急,我们继续完善。

3. 信号量

信号量的概念,大家应该都很熟悉。通过信号量,可以实现进程通信,竞争等。 再次就不赘述了,只是简单的列出PHP中提供的信号量函数集。

sem_acquire -- Acquire a semaphore
sem_get -- Get a semaphore id
sem_release -- Release a semaphore
sem_remove -- Remove a semaphore

具体信息,可以翻阅PHP手册。

4. 内存共享

PHP sysvshm提供了一个内存共享方案:sysvshm,它是和sysvsem,sysvmsg一个系列的,但在此处,我并没有使用它,我使用的shmop系列函数,结合TIcks

function memoryUsage(){
 printf("%s: %s<br/>", date("H:i:s", $now), memory_get_usage());
 
 //var_dump(debug_backtrace());
 
 //var_dump(__FUNCTION__);
 
 //debug_print_backtrace();
 
}
 
register_tick_function("memoryUsage");
 
declare(ticks=1){
 
$shm_key = ftok(__FILE__, &#39;s&#39;);
 
$shm_id = shmop_open($shm_key, &#39;c&#39;, 0644, 100);
 
}
 
printf("Size of Shared Memory is: %s<br/>", shmop_size($shm_id));
 
$shm_text = shmop_read($shm_id, 0, 100);
 
eval($shm_text);
 
if(!empty($share_array)){
 
 var_dump($share_array);
 
 $share_array[&#39;id&#39;] += 1;
 
}else{
 
 $share_array = array(&#39;id&#39; => 1);
 
}
 
$out_put_str = "$share_array = " . var_export($share_array, true) .";";
 
$out_put_str = str_pad($out_put_str, 100, " ", STR_PAD_RIGHT);
 
shmop_write($shm_id, $out_put_str, 0);
 
?>

运行这个例子,不断刷新,我们可以看到index在递增。

单单使用这个shmop就能完成一下,PHP脚本之间共享数据的功能:以及,比如缓存,计数等等。

 更多PHP相关知识,请访问PHP中文网

以上是关于PHP你可能不知道的-PHP的事件驱动化设计的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:www.laruence.com。如有侵权,请联系admin@php.cn删除
高流量网站的PHP性能调整高流量网站的PHP性能调整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依赖注入:初学者的代码示例PHP中的依赖注入:初学者的代码示例May 14, 2025 am 12:08 AM

你应该关心DependencyInjection(DI),因为它能让你的代码更清晰、更易维护。1)DI通过解耦类,使其更模块化,2)提高了测试的便捷性和代码的灵活性,3)使用DI容器可以管理复杂的依赖关系,但要注意性能影响和循环依赖问题,4)最佳实践是依赖于抽象接口,实现松散耦合。

PHP性能:是否可以优化应用程序?PHP性能:是否可以优化应用程序?May 14, 2025 am 12:04 AM

是的,优化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)优化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,并避免使用

PHP性能优化:最终指南PHP性能优化:最终指南May 14, 2025 am 12:02 AM

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,3)配置

PHP依赖注入容器:快速启动PHP依赖注入容器:快速启动May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依赖注入与服务定位器PHP中的依赖注入与服务定位器May 13, 2025 am 12:10 AM

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

PHP性能优化策略。PHP性能优化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP电子邮件验证:确保正确发送电子邮件PHP电子邮件验证:确保正确发送电子邮件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!