最近在做一個需要用到異步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__, 'm'); $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__, 's'); $shm_id = shmop_open($shm_key, 'c', 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['id'] += 1; }else{ $share_array = array('id' => 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中文網其他相關文章!

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver Mac版
視覺化網頁開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版
中文版,非常好用

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!