簡體   English   中英

多次包含php文件的foreach循環-可以接受嗎?

[英]foreach loop that include php files multiple times - acceptable?

我有此函數“ processMessage($ msg)”,該函數根據字符串中的前幾個字(前綴)來處理字符串。

我從數據庫中拉出許多行,並通過上述函數傳遞每個$ msg字符串...

需要注意的是,該函數不具有“ if($ prefix =='blah')”條件,而是包括一堆包含這些條件的php文件。

為什么?

因為我不想在一個函數中對一組條件進行硬編碼,而是希望通過單獨的php文件來組織每個條件,以實現可移植性,自定義性等(這里有很長的故事)

所以基本上看起來像這樣(保持代碼簡單):

主腳本從數據庫加載行並將消息放入$ msg_r數組中,然后循環遍歷每個msg,如下所示:

foreach (msg_r as $key=>$msg){
    processMsg($msg);
}

實際的處理器功能:

function processMsg($msg){

    $msg_r = explode(" ",$msg); // break apart message based on spaces .. eg. "reboot machine 30"
    //prepare prefixes
    $prefix1 = $msg_r[0];// reboot
    $prefix2 = $msg_r[1];// machine
    $prefix3 = $msg_r[3];// 30

    //process the above prefixes.. but instead of hard coding multiple if conditions here, load if else conditions from files. 
    require("condition1.php");
    require("condition2.php");
    require("condition3.php");
    //my actual require code is in a loop that loads all files found in a target directory


}

條件文件基本上只是用於ifif條件的php代碼,例如:

if($prefix1 == 'reboot' and $prefix2 == 'machine') {
// do something
}

因此,這是一個簡單的設置,似乎可以在我的測試過程中使用,但是我想知道這是“正常”策略還是“可接受”策略,或者您是否可以建議其他方法?

關於所有

使用函數數組,並讓每個包含文件定義一個函數並將其推入數組。 因此,主腳本將包含:

$test_array = array();
require ("condition1.php");
require ("condition2.php");
...

包含文件將執行以下操作:

$test_array[] = function($prefix1, $prefix2, $prefix3) {
    if ($prefix1 == 'reboot' && $prefix2 == 'machine') {
        // do something
    }
};

您的主要功能將是:

function processMsg($msg){
    global $test_array;

    $msg_r = explode(" ",$msg); // break apart message based on spaces .. eg. "reboot machine 30"
    //prepare prefixes
    $prefix1 = $msg_r[0];// reboot
    $prefix2 = $msg_r[1];// machine
    $prefix3 = $msg_r[3];// 30

    foreach ($test_array as $test) {
        $test($prefix1, $prefix2, $prefix3);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM